Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sure NSUserDefaults settings get saved to disk when the app quits?

For some reason, since multitasking has arrived, NSUserDefaults seem to not save the settings to disk anymore every time the app closes.

This happens: When a setting is changed in NSUserDefaults and home button gets pressed, home screen becomes visible. app is still running in background. Then I press twice the home button, and remove the app from the task manager. App is now really quit. Then I tap the icon of the app to launch it again. Voilla: Settings not stored! wrong, old value!

But when I do this, it works: Press home button, tap app icon again, press home button again, and NOW double tap home button and kill the app. Tap icon again. Now the app shows the correct settings.

I never explicitely saved NSUserDefaults since it always worked fine. But now, iOS seems to be not clever enough to do that automatically... is there anything I can call in any of those "app will quit now" methods in the app delegate, so that the NSUserDefaults dict really gets saved?

like image 954
openfrog Avatar asked Jan 22 '23 09:01

openfrog


1 Answers

NSUserDefaults changes are saved when it's sent a synchronize message:

[[NSUserDefaults standardUserDefaults] synchronize];

The system calls this automatically only when the app terminates. The system also calls this every few seconds, which is why there's a noticeable delay in seeing your settings saved.

In iOS 4, the app doesn't actually completely terminate (aka quit) if you let it support multitasking. If you want to support multitasking anyway, and also want the user defaults to save whenever the app leaves the foreground, you can call the above message in applicationDidEnterBackground: of your app delegate, like so:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [[NSUserDefaults standardUserDefaults] synchronize];
}
like image 91
BoltClock Avatar answered Apr 06 '23 11:04

BoltClock