BeachRunnerFred
BeachRunnerFred

Reputation: 18558

Why doesn't my NSUserDefault value get written?

I'm trying to make use of NSUserDefaults to keep track of some promotional data in my iOS app, but it's not working like I'm expecting it to. Here's the code...

 NSString *promoID = [[[self currentPromo] allKeys] objectAtIndex:0];

 if(![[NSUserDefaults standardUserDefaults] boolForKey:[NSString stringWithFormat:@"promoid-%@", promoID]])
 {
     [[NSUserDefaults standardUserDefaults] setBool:YES forKey:[NSString stringWithFormat:@"promoid-%@", promoID]];
 .
 .
 .

Everytime this if statement is executed, the code inside is executed. Shouldn't the code inside this if statement only execute once?

Thanks so much for your wisdom!

Upvotes: 1

Views: 572

Answers (2)

Saranya
Saranya

Reputation: 1521

Use synchronize keyword to retrieve your data in NSUserDefaults

[[NSUserDefaults standardUserDefaults] synchronize];

This will retrieve and display the data.

Upvotes: 1

cweinberger
cweinberger

Reputation: 3588

Depends on how fast you go through this again.

NSUserDefaults are not synchronized instantly. If you want to do this, you need to call [[NSUserDefaults standardUserDefaults] synchronize]; after setting a value.

Upvotes: 4

Related Questions