While my iPhone app is running I store some data (NSStrings) in the NSUserDefaults. I'm storing the high score for a game just fyi. When I double-tap the home button and kill the app the values I store in NSUserDefaults are often not there when I restart the app. Why is this happening?
The code I'm using was working fine in all the pre-multitasking OSs (3.0 etc). From reading/searching the net it looks like doing [NSUserDefaults standardUserDefaults] synchronize]; could help. Any thoughts?
Thanks!
Where are you calling the -synchronize method? Are you paying attention to the app delegate messages sent by the OS that let you know your app is about to go down?
Killing an app from the taskbar when it's suspended just sends it the SIGKILL message; no graceful shutdown happens.
If you're backgrounding and then killing the app, you might not be getting the user defaults synchronized (written to disk) before the app dies, which happens by itself on an internal timer usually, but if you've written to the defaults and then the thing gets suspended before the auto-synchronize happens, that could explain this behavior.
Put this (as you note):
in your
-applicationDidEnterBackground
handler in the app delegate. That way, even if the app dies or is killed while it's in the background, you know the defaults have been written.As a defensive practice, I generally explicitly call synchronize on the defaults object every time I write state that I consider critically important.
I'm not sure if this is it, but have you called
[[NSUserDefaults standardUserDefaults] registerUserDefaults:...]
?