Why is NSUserDefaults not saving my values?

If you terminate your app by pressing the home button (in the Simulator or on the device), your NSUserDefaults will get saved.

If you terminate your app by pressing "Stop" in Xcode (in the Simulator or on the device), your NSUserDefaults might get saved, but there's a good chance they won't. NSUserDefaults persists any changes periodically, and if you terminate the process before they've been persisted, they'll be gone. You can force the save by calling:

[[NSUserDefaults standardUserDefaults] synchronize];



Addendum:

In iOS4 (this answer was originally written when iOS3 was the public release), your NSUserDefaults may not get saved when pressing the home button. Manually calling [[NSUserDefaults standardUserDefaults] synchronize] in applicationDidEnterBackground: should ensure that your NSUserDefaults are saved correctly (this should really be a built-in behaviour IMO).


This code works fine for me .

NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

if (standardUserDefaults) {
    [standardUserDefaults setObject:myString forKey:@"Prefs"];
    [standardUserDefaults synchronize];
}