6

My [NSUserDefaults standardUserDefaults] are not being saved. Everytime I close the app and start it again, it reverts back. I don't have my iOS device handy so I am not sure if this will happen on device, but none of the other apps are doing this in simulator which leads me to believe there's something wrong with my code. I don't know what part of code I should include here, it's just simple add/modify keys in NSUserDefaults and as I said it runs fine during the app, but not after i restart it...

I know I can call synchronize but Apple advices against it and says I should only call it if it's a must... so.

What could be going wrong?

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
user635064
  • 6,219
  • 12
  • 54
  • 100
  • 1
    why don't you try and call synchronize just to see if it works? you can also check its return value for errors... – sergio May 17 '11 at 15:47
  • Hi, I just did that at applicationwillterminate method, but doesn't work.. :( – user635064 May 17 '11 at 15:59
  • Try to do it in `applicationDidEnterBackground:`, as I suggest in my answer below. See this for more details: http://stackoverflow.com/questions/3139588/applicationwillterminate-in-ios-4-0 – sergio May 17 '11 at 16:11

3 Answers3

10

Your process is possibly terminated improperly so that NSUserDefaults do not have a chance to be stored. See also this and mostly this.

The suggestion in the second post I link to is to call synchronize in applicationDidEnterBackground:

Keep also in mind that terminating your app by stopping it in Xcode most often does not save user defaults.

Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
sergio
  • 68,819
  • 11
  • 102
  • 123
  • Sergio is right. If you want your values to be saved in the simulator when you quit out, you **have** to call `synchronize`. – Shaolo Apr 16 '13 at 03:06
1

Are you restarting from Xcode / debugger? Try sending the app to background with the Home button first. I think the framework synchronizes automatically then.

Steven Kramer
  • 8,473
  • 2
  • 37
  • 43
  • Hi, Thanks for your reply, I send it to background and then double clicked the home button and closed the app. Then, when I start it from simulator again, it crashed. But in XCode if I build -> run, it doesn't crash, but my nsuserdefaults aren't saved...hmm – user635064 May 17 '11 at 15:50
0

I could not understand about the way, you are accessing the NSUserDefault, The static function you used sharedDefaults with NSUserDefault does'nt exist in Apple Documentation

Use As below to access NSUserDefault

[NSUserDefaults standardUserDefaults];

For more read the blog post for using of NSUserDefault.

iPhone Programming Tutorial – Saving/Retrieving Data Using NSUserDefaults

Jhaliya - Praveen Sharma
  • 31,697
  • 9
  • 72
  • 76