Hunter Mitchell
Hunter Mitchell

Reputation: 7293

Saving NSUserDefaults Issue?

i have been working on a app, and needed to store a string. I used this code to set the default:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:CertificateKey.stringValue forKey:@"SavedKey"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(@"%@",[defaults objectForKey:@"SavedKey"]);

I loged it, so i know it saved...well, it showed me the value. When i open my application, I use this to retrieve the default:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[CertificateKey setStringValue:[defaults objectForKey:@"SavedKey"]];
[CertificateKey setTitleWithMnemonic:[defaults objectForKey:@"SavedKey"]];
[[NSUserDefaults standardUserDefaults] synchronize];

Why will it not get the default value? Did i not completely save it?

Upvotes: 0

Views: 188

Answers (2)

Ramy Al Zuhouri
Ramy Al Zuhouri

Reputation: 21966

Don't quit the application by pressing the stop button in xcode. Instead, quit it by right clicking on the application icon and selecting "Quit".

Edit

Maybe the first time that you execute the application, you want to save some defaults but you don't want to set them the second+ time that the application runs.

For this purpose in some class initialize method register the defaults, like this:

+ (void) initialize
{
    NSUserDefaults* defaults= [NSUserDefaults standardUserDefaults];
    [defaults registerDefaults: @{} ];
    // This case it's an empty dictionary, but you can put whatever you want inside it.
    // just convert it to data if it's not an object storable to a plist file.
}

Also, you're using setValue:forKey: , that method is inherited from NSObject. Use setObject:forKey: .

And use finalize if you want to save the defaults at the end:

- (void) finalize
{
    // Save the defaults here
}

Upvotes: 2

terry lewis
terry lewis

Reputation: 672

You might have a problem because you are creating an instance of NSUserDefaults. From what I understand you are supposed to access it like so: [[NSUserDefaults standardUserDefaults] setValue:@"Pikachu" forKey:@"Best Pokemon Ever"]; [[NSUserDefaults standardDefaults] objectForKey:@"Best Pokemon Ever"]; Rather than actually creating an instance of it.

Upvotes: -1

Related Questions