Ian*_*mis 51 nsdictionary nsdata ios swift
我不确定我是否正在使用字典或数据对象或两者都不正确.我试图习惯切换到快速但我有点麻烦.
var dictionaryExample : [String:AnyObject] =
["user":"UserName",
"pass":"password",
"token":"0123456789",
"image":0] // image should be either NSData or empty
let dataExample : NSData = dictionaryExample as NSData
Run Code Online (Sandbox Code Playgroud)
我需要NSDictionary编码到一个NSData对象以及获取该NSData对象并将其解码为NSDictionary.
非常感谢任何帮助,谢谢.
Leo*_*Leo 110
你可以使用NSKeyedArchiver和NSKeyedUnarchiver
swift 2.0+的示例
var dictionaryExample : [String:AnyObject] = ["user":"UserName", "pass":"password", "token":"0123456789", "image":0]
let dataExample : NSData = NSKeyedArchiver.archivedDataWithRootObject(dictionaryExample)
let dictionary:NSDictionary? = NSKeyedUnarchiver.unarchiveObjectWithData(dataExample)! as? NSDictionary
Run Code Online (Sandbox Code Playgroud)
Swift3.0
let dataExample: Data = NSKeyedArchiver.archivedData(withRootObject: dictionaryExample)
let dictionary: Dictionary? = NSKeyedUnarchiver.unarchiveObject(with: dataExample) as! [String : Any]
Run Code Online (Sandbox Code Playgroud)
操场截图
NSPropertyListSerialization可能是一种替代解决方案.
// Swift Dictionary To Data.
var data = try NSPropertyListSerialization.dataWithPropertyList(dictionaryExample, format: NSPropertyListFormat.BinaryFormat_v1_0, options: 0)
// Data to Swift Dictionary
var dicFromData = (try NSPropertyListSerialization.propertyListWithData(data, options: NSPropertyListReadOptions.Immutable, format: nil)) as! Dictionary<String, AnyObject>
Run Code Online (Sandbox Code Playgroud)
斯威夫特 5
正如@yuyeqingshan 所说,PropertyListSerialization是一个不错的选择
// Swift Dictionary To Data.
do {
let data = try PropertyListSerialization.data(fromPropertyList: [:], format: PropertyListSerialization.PropertyListFormat.binary, options: 0)
// do sth
} catch{
print(error)
}
// Data to Swift Dictionary
do {
let dicFromData = try PropertyListSerialization.propertyList(from: data, options: PropertyListSerialization.ReadOptions.mutableContainers, format: nil)
if let dict = dicFromData as? [String: Any]{
// do sth
}
} catch{
print(error)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70822 次 |
| 最近记录: |