nathandemick.com

How to Save Data with NSUserDefaults

A common requirement for any sort of computer program is saving data. In iOS, probably the simplest way of saving information about your app is using NSUserDefaults. In a nutshell, NSUserDefaults is a dictionary that will automatically save and load its' state when your app opens and closes. I've used the NSUserDefaults class to save preferences (such as music on or off), as well as store info about the player's progress through my game (whether a level is completed, best completion time, etc).

The best thing about NSUserDefaults is that it's super easy to use. To set a default value:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setBool:TRUE forKey:@"shouldPlayMusic"];
[defaults synchronize];

To get that same value back:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
Boolean shouldPlayMusic = [defaults boolForKey:@"shouldPlayMusic"];

And of course, the best part is that's all you have to do — you don't have to worry about serialization or saving to disk or whatever.

Another tip is that you can initialize your NSUserDefaults with a pre-defined NSDictionary object. So for example you could set a default value to be "false" or "true" before the user ever had a chance to interact with your program. In my case, sometimes I create an array that represents all the levels in my game, and in each array value I store a boolean to check if a player has finished the level. To do this I create the data object and then register it with NSUserDefaults. If a previous value exists for the object, then nothing happens. Otherwise my blank object gets saved as the "default" defaults.

Even better, you can define your standard defaults by using a .plist:

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults registerDefaults:[NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"UserDefaults" ofType:@"plist"]]];

In this example I've got a file named UserDefaults.plist in my project, which is a dictionary that has the default keys and objects I want my app to start with. For more examples, check out Apple's reference page.

· 3 comments


Comments

Mbi_studio wrote on :

Great! This worked perfectly!

Abhishek Sonawane wrote on :

great it worked for me as well,, I stored the image data in it.......

Understanding registerDefaults wrote on :

[…] Quoted from How to Save Data with NSUserDefaults […]