Saving NSUserDefaults under iOS 4

July 17, 2010

iOS4 introduced ‘multitasking’ wherein rather than being terminated your application is put into a suspended state where it’ll wait either until the user opens it again, the OS terminates it as it needs the resources or the user taps the ‘stop’ button in the task tray. (Oliver Drobnik has an excellent in-depth explanation of this.)

I encountered a problem today where my application didn’t seem to be saving the parameters I set in NSUserDefaults when the application finishes (I save some state based on the time the user exits. Usually I’d recommend updating the NSUserDefaults object as soon as the user finalises the action rather than at the end of the current application run).

I know some other people have been having this problem too so I thought I’d share the solution, as it’s exceedingly simple.

You need to call the synchronize method on your NSUserDefaults object.
[[NSUserDefaults standardUserDefaults] synchronize];

The OS periodically synchronizes the NSUserDefaults object while your application is running, apparently around every 15 seconds. It seems that when your application backgrounds sometimes it won’t be synchronized in time, if the user kills it from the tray or the OS reclaims the memory immediately. Manually calling synchronize will enforce a save and ensure your data is there next time.

Leave a Reply