NSDictionary到NSData和NSData到Swift中的NSDictionary [英] NSDictionary to NSData and NSData to NSDictionary in Swift
本文介绍了NSDictionary到NSData和NSData到Swift中的NSDictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不确定我是否正在使用字典或数据对象或两者都不正确。我试图习惯切换到swift但我遇到了一些麻烦。
I am not sure if I am using the dictionary or the data object or both incorrectly. I m trying to get used to the switch to swift but I'm having a little trouble.
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
。
I need the NSDictionary
to encode to an NSData
object as well as taking that NSData
object and decode it into a NSDictionary
.
非常感谢任何帮助,谢谢。
Any help is greatly appreciated, thanks.
推荐答案
您可以使用 NSKeyedArchiver
和 NSKeyedUnarchiver
swift 2.0 +示例
Example for 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]
游乐场的屏幕截图
这篇关于NSDictionary到NSData和NSData到Swift中的NSDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文