我不确定我是在使用字典还是数据对象,或者两者都使用不正确。我试图适应快速切换,但遇到了一些麻烦。

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

非常感谢任何帮助,谢谢。

最佳答案

您可以使用NSKeyedArchiverNSKeyedUnarchiver
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

Swift3.0
let dataExample: Data = NSKeyedArchiver.archivedData(withRootObject: dictionaryExample)
let dictionary: Dictionary? = NSKeyedUnarchiver.unarchiveObject(with: dataExample) as! [String : Any]

游乐场的屏幕截图

ios - 在Swift中将NSDictionary转换为NSData并将NSData转换为NSDictionary-LMLPHP

关于ios - 在Swift中将NSDictionary转换为NSData并将NSData转换为NSDictionary,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26376469/

10-09 06:45