somepers
somepers

Reputation: 529

NSUserDefaults doesn't save after app quits

When I quit the app, the values stored in NSUserDefaults isn't saved. I saved the values like this:

[[NSUserDefaults standardUserDefaults] setValue:@"enabled" forKey:@"notifications"];
[[NSUserDefaults standardUserDefaults] synchronize];

How do I store something with NSUserDefaults even after the app quits?

This is how I retrieve the values:

[[NSUserDefaults standardUserDefaults] valueForKey:@"notifications"]

The first two lines do run, because I put them to run when a button is pressed. When I go to a different view and back to the one with the button, it returns the value that I set.

I see what was wrong. I has this code in the first view and assumed it was working properly:

NSUserDefaults *Def = [NSUserDefaults standardUserDefaults];
NSString *Ver = [Def stringForKey:@"Version"];
NSString *CurVer = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString*)kCFBundleVersionKey];
if(Ver == nil || [Ver compare:CurVer] != 0)
{
    if(Ver == nil)
    {
        [[NSUserDefaults standardUserDefaults] setValue:@"disabled" forKey:@"notifications"];
    }
}

Upvotes: 0

Views: 824

Answers (1)

Mick MacCallum
Mick MacCallum

Reputation: 130193

You're using the wrong methods.

valueForKey and setValue:forKey: are methods pertaining to Key Value Coding, and aren't related to setting your persistent data in NSUserDefaults.

You need to be reading your values with

[[NSUserDefaults standardUserDefaults] objectForKey:@"notifications"];

and writing with

[[NSUserDefaults standardUserDefaults] setObject:@"enabled" forKey:@"notifications"];

Upvotes: 2

Related Questions