Using NSUserDefaults in iPhone app – Interesting fact.

Using NSUserDefaults in iPhone app – Interesting fact.

In one of my projects, I was using User Defaults for the first time. Then I came across a very interesting problem. I was writing this code for setting value to user defaults:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:@”Value” forKey:@”key”];

After setting the values this way, I tried retrieving the value for the key in next session, it simply did not return correct value.

After googling for a while, I came to know about this line and it worked perfectly:

[prefs synchronize];

Thus, I came to know that in order to use User Defaults, one have to use this synchronize function. The final code looks like:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:@”Value” forKey:@”key”];
[prefs synchronize];

Enjoy!

Leave a Reply

Your email address will not be published. Required fields are marked *