【问题标题】:NSDictionary to NSData and NSData to NSDictionary in SwiftNSDictionary 到 NSData 和 NSData 到 Swift 中的 NSDictionary
【发布时间】:2014-10-15 07:07:59
【问题描述】:

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

我需要将NSDictionary 编码为NSData 对象,并将NSData 对象解码为NSDictionary

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

【问题讨论】:

  • 你真正想要达到什么目的?如果您不指定 NSData 的格式,那么说“将 NSDictionary 转换为 NSData”是没有意义的。

标签: ios swift nsdictionary nsdata


【解决方案1】:

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)
        }

【讨论】:

    【解决方案2】:

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

    操场截图

    【讨论】:

    • 您确实回答了我在标题中指定的问题。我认为 AnyObject 是错误的。我想让用户/通行证/令牌是字符串,图像是 nsdata 对象。我能做到吗?还是应该将它们全部编码为 NSData 对象,然后再解码?
    • 类 func unarchiveObjectWithData(data: NSData) -> AnyObject?这是来自 xocde 的文档。
    • 没关系,当我最终使用它们时,我只是说 data.valueForKey("user") as string 感谢您的帮助,该线程现在可以关闭
    • 这不起作用。这会产生错误'AnyObject' is not convertible to 'NSDictionary';
    • @c.dunlap 我已经更新了代码。我在 swift 1.2 时回答了答案。所以,对于 swift 2.0,它可能有一些语法问题
    【解决方案3】:

    对于 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
    

    【讨论】:

    • 不好的例子。您说“Swift 4”,但您将 NSData 转换为 Data 而不是直接使用 Data,您使用的是 AnyObject 而不是 Any,而且您对选项的使用远非最佳......
    【解决方案4】:

    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>
    

    【讨论】:

      【解决方案5】:

      对于 Swift 3:

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

      【讨论】:

        【解决方案6】:

        Leo's answer 给了我构建时间错误,因为NSDataData 不同。函数unarchiveObject(with:) 接受Data 类型的变量,而函数unarchiveTopLevelObjectWithData() 接受NSData 类型的变量。

        这是一个有效的 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")
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2018-07-17
          • 1970-01-01
          • 1970-01-01
          • 2019-01-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多