ios Swift 中 NSDictionary 到 NSData 和 NSData 到 NSDictionary

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26376469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 03:12:45  来源:igfitidea点击:

NSDictionary to NSData and NSData to NSDictionary in Swift

iosswiftnsdictionarynsdata

提问by IanTimmis

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.

我不确定我是否错误地使用了字典或数据对象或两者。我正在尝试习惯切换到 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

I need the NSDictionaryto encode to an NSDataobject as well as taking that NSDataobject and decode it into a NSDictionary.

我需要NSDictionary对一个NSData对象进行编码,以及将该NSData对象解码为NSDictionary.

Any help is greatly appreciated, thanks.

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

回答by Leo

You can use NSKeyedArchiverand NSKeyedUnarchiver

您可以使用NSKeyedArchiverNSKeyedUnarchiver

Example for swift 2.0+

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

斯威夫特3.0

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

Screenshot of playground

游乐场截图

enter image description here

在此处输入图片说明

回答by yuyeqingshan

NSPropertyListSerialization may be an alternative solution.

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>

回答by ingconti

For Swift 3:

对于 Swift 3:

let data = try PropertyListSerialization.data(fromPropertyList: authResponse, format: PropertyListSerialization.PropertyListFormat.binary, options: 0)

回答by Ujjwal-Nadhani

Leo's answergave me build time errors because NSDataisn't the same as Data. The function unarchiveObject(with:)takes a variable of type Data, whereas the function unarchiveTopLevelObjectWithData()takes a variable of type NSData.

Leo 的回答给了我构建时间错误,因为NSDataData. 该函数unarchiveObject(with:)接受一个类型的变量Data,而该函数unarchiveTopLevelObjectWithData()接受一个类型的变量NSData

This is a working Swift 3answer:

这是一个有效的Swift 3答案:

var names : NSDictionary = ["name":["John Smith"], "age": 35]
let namesData : NSData = NSKeyedArchiver.archivedData(withRootObject: names) as NSData
do{
    let backToNames = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(namesData) as! NSDictionary
    print(backToNames)
}catch{
    print("Unable to successfully convert NSData to NSDictionary")
}

回答by DNG

Swift 5

斯威夫特 5

as @yuyeqingshan said, PropertyListSerializationis a good option

正如@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)
        }

回答by Abhishek Mishra

For Swift 4 -

对于 Swift 4 -

let dictionaryExample : [String:AnyObject] = ["user":"UserName" as AnyObject, "pass":"password" as AnyObject, "token":"0123456789" as AnyObject, "image":0 as AnyObject]
    let dataExample : NSData = NSKeyedArchiver.archivedData(withRootObject: dictionaryExample) as NSData
    let dictionary:NSDictionary? = NSKeyedUnarchiver.unarchiveObject(with: dataExample as Data)! as? NSDictionary