我不确定我是否在使用字典或数据对象,或者两者都不正确。我正试着习惯改用斯威夫特,但我遇到了一点小麻烦。
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我需要NSDictionary对NSData对象进行编码,并将该NSData对象解码为NSDictionary。
任何帮助都是非常感谢的,谢谢。
发布于 2014-10-15 07:15:28
您可以使用NSKeyedArchiver和NSKeyedUnarchiver
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? NSDictionarySwift3.0
let dataExample: Data = NSKeyedArchiver.archivedData(withRootObject: dictionaryExample)
let dictionary: Dictionary? = NSKeyedUnarchiver.unarchiveObject(with: dataExample) as! [String : Any]操场截图

发布于 2016-07-11 03:05:57
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>发布于 2020-05-04 05:36:53
Swift 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)
}https://stackoverflow.com/questions/26376469
复制相似问题