Strange NSUserDefaults behavior
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!
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):
[[NSUserDefaults standardUserDefaults] synchronize];
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.
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?
I'm not sure if this is it, but have you called [[NSUserDefaults standardUserDefaults] registerUserDefaults:...]
?
精彩评论