1

I have saved an NSString in my NSUserDefault with key @"userKey".
I want to be able to reset this value to @"" when the app is totally shut down but not when it enters the background.

I have tried:

[[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"opponentFile"];

in my appdelegate's -applicationWillTerminate: but nothing happens.

When I open the app after completely closing it the default value is still there.
How do I do this?

staticVoidMan
  • 19,275
  • 6
  • 69
  • 98
user1114881
  • 731
  • 1
  • 12
  • 25

2 Answers2

4

Permanent NSUserDefaults changes are scheduled at intervals.
You can instead force this by adding the following to your -applicationWillTerminate:.

[[NSUserDefaults standardUserDefaults] synchronize];

Don't force this too frequently as it tends to reduce your app performance.


Or... you can just do

[[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"opponentFile"];

in the -didFinishLaunchingWithOptions: instead.
Seems like the same thing to me.

staticVoidMan
  • 19,275
  • 6
  • 69
  • 98
  • I put `[[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"opponentFile"];` in the -didFinishLaunchingWithOptions: and it worked great thx – user1114881 Jul 26 '14 at 19:31
0

Try instead:

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application;
vikingosegundo
  • 52,040
  • 14
  • 137
  • 178
ppalancica
  • 4,236
  • 4
  • 27
  • 42
  • I'd advise against it, this method is not called when the app closes, only when the device is short on memory. He wants to reset his value upon app exit, so we need applicationWillTerminate instead as suggested by staticVoidMan. – Jay Versluis Jul 25 '14 at 01:50