views:

62

answers:

2

I have the following code in my applicationWillTerminate in the app delegate:

NSLog(@"Source: %d", [[NSUserDefaults standardUserDefaults] integerForKey:@"Source"]);

And I have the same code in my applicationDidFinishLaunching in the same app delegate.

When I quit the app, the log shows one value (say 101) and when I relaunch the app, the log shows another value (say 105). Subsequently changing the value (say to 102) in the user defaults works correctly since when I quit app again, the correct value (this time 102) is logged in the applicationWillTerminate method. However, relaunching the app logs 105 repeatedly irrespective of what the value is changed to.

If I remove the app from the simulator and relaunch it, an entirely different value is shown on launch and this value is consistently shown for subsequent launches.

I have no clue what's happening here. Anyone has any ideas?

+3  A: 

I don't know about the value changing between launches with no effort on your part, but when you set the value for a preference key the value isn't "saved". You need to call synchronize on the NSUserDefault object first.

e.g.

[_defaults setInteger:1 forKey:@"key"];
[_defaults synchronize];
freespace
it worked...Thanks Freespace
Raviraja
A: 

Thanks for pointing out to synchronize, helped a lot :D

rick