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

I put the code inside my AppDelegate, but when I started the application again, I noticed that the values ​​are still persistent (not NULL). Why is this?

Code:

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

Thanks.

+4
source share
4 answers

Instead of NULL you should use -removeObjectForKey: The former is the official way to remove values, and the latter is undocumented behavior.

In any case, if using -removeObjectForKey: does not work, you can add a call

 [[NSUserDefaults standardUserDefaults] synchronize]; 

in the end. But just do it if it doesn't work without him. The reason is that the -synchronize call -synchronize (relatively) expensive, so it needs to be done only when necessary to ensure correctness.


After another look, I suspect that your real problem is that this method is not called at all. On iOS 4 and later, when applications enter the background, they do not call this method, instead they call -applicationDidEnterBackground: Instead, you should try putting this code.

+9
source

In this case, I expect that you will need to manually call the synchronization method in NSUserDefaults as the last line in this method to make sure that it synchronizes before the application terminates.

+3
source

try this method:

 - (void)removeObjectForKey:(NSString *)defaultName 
0
source
  NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults]; if (prefs) { [prefs setObject:NULL forKey:@"roomCat"]; [prefs synchronize]; } 
0
source

Source: https://habr.com/ru/post/1391530/


All Articles