Write/Read data using NSUserDefaults

Here I will show you how to use NSUserDefaults to save data.
This method is very simple but very slow, so it’s not good to use it to storage a big data.

Just add this line to setup :

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

And to read data use:

int value;
value = [prefs intForKey:@”value”];

To write data:

int value = 1;

[prefs setInteger:value forKey:@”value”];
[prefs synchronize];

Remember to synchronize after all saves, not at the end.

Of course you can write/read other data types.

From Mac Dev Center:

– setBool:forKey:
– setFloat:forKey:
– setInteger:forKey:
– setObject:forKey:
– setDouble:forKey:
– setURL:forKey:

In my apps I use it to check whether the app runs at the first time or not.

Just do something like this:

if ([prefs boolForKey:@”first_time”] == 0)
{
// First run
[prefs setBool:1 forKey:@”first_time”];
[prefs synchronize];
}
else
{
// Second run

}

It works becouse all unsaved data are from default 0.

Responses

  1. Excellent Thank you so much!!!

  2. excellent work man

  3. You saved my day. Thx so much.
    Sitting here close to midnight and found your script. Woooooeeee. 🙂

  4. Thanks for helping !


Leave a reply to brunohdcBruno Cancel reply