NSDictionary to NSData and NSData to NSDictionary in Swift

前端 未结 6 1456
故里飘歌
故里飘歌 2020-12-12 23:54

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.

         


        
6条回答
  •  鱼传尺愫
    2020-12-13 00:15

    You can use NSKeyedArchiver and NSKeyedUnarchiver

    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]
    

    Screenshot of playground

提交回复
热议问题