Storing a dictionary in swift in permanent storage

痴心易碎 提交于 2019-12-24 12:04:43

问题


this code here throws an error when I run the app

var dic :[NSObject: AnyObject] = ["name":"steph" , "status": "unemployed"]

NSUserDefaults.standardUserDefaults().setObject(array, forKey: "diction")

var retrievedDict = NSUserDefaults.standardUserDefaults().objectForKey("diction")! as NSDictionary

let g = dic["name"]

println(g)

what's wrong with this?


回答1:


The problem is that the Dictionary key has to be a String. So instead of declaring it [NSObject: AnyObject] you have to declare it as [String: AnyObject]. Also you are trying to load it from dic but you have to load it from retrievedDict.

update: Xcode 7.2 • Swift 2.1.1

let dic:[String: AnyObject] = ["name":"steph" , "status": "unemployed"]

NSUserDefaults().setObject(dic, forKey: "diction")

if let retrievedDict = NSUserDefaults().dictionaryForKey("diction") {
    if let g = retrievedDict["name"] as? String {
        print(g)
    }
}



回答2:


Your code is fine. Your only problem is, that you pass the wrong object to your NSUserDefaults. You should pass the dic instead of array.

So change that:

NSUserDefaults.standardUserDefaults().setObject(array, forKey: "diction")

to that:

NSUserDefaults.standardUserDefaults().setObject(dic, forKey: "diction")


来源:https://stackoverflow.com/questions/28662331/storing-a-dictionary-in-swift-in-permanent-storage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!