How to make sure that NSUserDefaults settings are saved to disk when the application terminates?

For some reason, since multitasking has come, NSUserDefaults seem to no longer save settings to disk every time the application closes.

This happens: When you change the settings in NSUserDefaults and press the home button, the main screen becomes visible. the app is still running in the background. Then I double-click the home button and delete the application from the task manager. The application is now truly discontinued. Then I click the application icon to start it again. Voilla: settings not saved! wrong old value!

But when I do this, it works: press the "home" button, click the application icon again, press the "home" button again, and "NOW" double-click the "home" button and kill the application. Click the icon again. Now the application shows the correct settings.

I have never explicitly saved NSUserDefaults since it always worked fine. But now iOS doesn't seem smart enough to do it automatically ... is there anything I can call in any of these “app will quit now” methods in the app’s folder, so the NSUserDefaults file will really be saved?

+4
source share
1 answer

NSUserDefaults changes are saved when a synchronize message is sent:

 [[NSUserDefaults standardUserDefaults] synchronize]; 

The system calls this automatically only when the application terminates. The system also calls this every few seconds, so there is a noticeable delay in saving the settings.

In iOS 4, the application doesn’t actually complete completely (aka quit) if you allow it to support multitasking. If you want to support multitasking in any case, and also want custom defaults to be saved whenever the application leaves the foreground, you can call the above message in applicationDidEnterBackground: your application delegate, for example:

 - (void)applicationDidEnterBackground:(UIApplication *)application { [[NSUserDefaults standardUserDefaults] synchronize]; } 
+9
source

All Articles