NSDictionary to NSData and NSData to NSDictionary in Swift

前端 未结 6 1457
故里飘歌
故里飘歌 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:18

    Leo's answer gave me build time errors because NSData isn'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.

    This is a working Swift 3 answer:

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

提交回复
热议问题