Storing a dictionary in swift in permanent storage

2019-08-13 05:44发布

问题:

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