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

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: