Strange NSUserDefaults behavior

2019-05-18 18:25发布

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!

3条回答
家丑人穷心不美
2楼-- · 2019-05-18 18:48

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?

查看更多
何必那么认真
3楼-- · 2019-05-18 18:50

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.

查看更多
淡お忘
4楼-- · 2019-05-18 18:56

I'm not sure if this is it, but have you called [[NSUserDefaults standardUserDefaults] registerUserDefaults:...]?

查看更多
登录 后发表回答