Use NSUserDefaults to persist data between app runs

On the iPhone you generally want your application to start looking like it did when it was last run to give the user the impression your app is ready to pick up where it left off. NSUserDefaults provides an easy way to store your application’s settings between runs. Simply create an instance of NSUserDefaults and give it the key/value pairs you want it to save.

Storing an integer

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger: myIntValue forKey: @"intValueKey"];
[prefs synchronize]; // writes modifications to disk

Reading it back in

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
int myIntValue = [prefs integerForKey: @"intValueKey"];

or more simply

int myIntValue = [[NSUserDefaults standardUserDefaults] integerForKey: @"intValueKey"];

Of course, this would be pretty useless if it only worked for integers. The same basic syntax also works for setObject/objectForKey and some others. Check the documentation for details. I have not tried with complicated compound objects yet, but NSUserDefaults so far I have had success with strings and simple arrays.

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