I read a lot on Stack Overflow regarding this question, namely, Swift NSUserDefaults not saving Dictionary?, Saving dictionary into NSUserDefaults, and Store and update a Swift Dictionary in NSUserDefaults Xcode. However, I cannot seem to find a solution that works.
Someone graciously provided snippet of code that worked for him or her but it's not working for me and I'm not exactly sure why. Here is what I tried:
var addressDict = Dictionary<Int, Array<String>>()
addressDict[3] = ["string1", "string2"] //some example values
let data = NSKeyedArchiver.archivedDataWithRootObject(addressDict) //archiving
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(data, forKey: "address") //storing
if let data2 = defaults.objectForKey("address") as? NSData { //reading
let addressDict2 = NSKeyedUnarchiver.unarchiveObjectWithData(data2) //unarchiving
print(addressDict2)
}
I ran this snippet of code. And then I commented out addressDict[3] = ["string1", "string2"]
and ran the application again. However, it seemed to be not saved onto memory since when this line of code executed print(addressDict2)
, there was no data in the dictionary. Anybody have a solution to solve this? Thank you in advance for your help! :)