0

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! :)

Community
  • 1
  • 1
Jae
  • 321
  • 3
  • 12
  • Try to sync the user defaults after setObject – Rick van der Linde Aug 28 '15 at 21:13
  • Have you commented the saving line too? Or you expect that after you save an empty dictionary, you'll read the previous value? – Sega-Zero Aug 28 '15 at 21:13
  • @Rick van der Linde I tried to sync the user defaults by `NSUserDefaults.standardUserDefaults().synchronize()` after setObject, but it did not work. @Sega-Zero I apologize but I'm not exactly sure what you mean. – Jae Aug 28 '15 at 21:22
  • have you removed the line `defaults.setObject(data, forKey: "address") //storing` ? – Sega-Zero Aug 28 '15 at 21:23
  • Thank you so so so much @Sega-Zero. Yes it worked!!! But why?! – Jae Aug 28 '15 at 21:32
  • 1
    You instantiate a new variable an it's empty. then you write to defaults and then read it. What will be in defaults after you write an empty dictionary to it? :) – Sega-Zero Aug 28 '15 at 21:33
  • OOOOOOOOO. Okay I see. Thank you so much. – Jae Aug 28 '15 at 21:36

0 Answers0