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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With