Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUserDefaults written in -applicationWillTerminate: do not take effect; Why?

I have put the code below inside my AppDelegate, but when I start the app again I notice that the values are still saved (Not NULL). Why is that?

The code:

    - (void)applicationWillTerminate:(UIApplication *)application
{       [[NSUserDefaults standardUserDefaults]
         setObject:NULL forKey:@"roomCat"];
        [[NSUserDefaults standardUserDefaults]
         setObject:NULL forKey:@"TFA"];
        [[NSUserDefaults standardUserDefaults]
        setObject:NULL forKey:@"comments"];

}

Thank you.

like image 578
Bobj-C Avatar asked Dec 16 '22 05:12

Bobj-C


2 Answers

You should be using -removeObjectForKey: instead of setting NULL. The former is the official way to remove values, while the latter is undocumented behavior.

In any case, if using -removeObjectForKey: doesn't work, then you can add a call to

[[NSUserDefaults standardUserDefaults] synchronize];

at the end. But only do that if it doesn't work without it. The reason being because calling -synchronize is (relatively) expensive, so it should only be done when required to ensure correctness.


After taking another look, I suspect your real problem is this method isn't being called at all. On iOS 4 and later, when apps enter the background, they don't call this method, instead they call -applicationDidEnterBackground:. You should try putting this code there instead.

like image 98
Lily Ballard Avatar answered Dec 21 '22 23:12

Lily Ballard


In this case, I would expect that you would need to manually call the synchronize method on NSUserDefaults as the last line in this method to ensure it syncs before the application terminates.

like image 33
dtuckernet Avatar answered Dec 22 '22 01:12

dtuckernet