Storing to NSUserDefaults

Persistent Data

One of the nice things about the iPhone SDK is the NSUserDefaults helpers. NSUserDefaults allows you to persist data across sessions (whether your users presses the home button or gets interupted by a text/call). This can be useful for saving data regarding the current session (in my case the game state) and also for saving user defined settings from within your app.

The NSUserDefaults classes can store and NS-data type variables (NSString, NSInteger, NSData, etc) across user sessions, so it’s pretty handy! Here is my example code, it shows saving, accessing and deleting objects from the NSUserDefaults.

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
//store an (NS)integer
[prefs setInteger: myIntValue forKey: @"intValueKey"];

//store any other NS data object (NSString, NSData, etc)
[prefs setObject:data forKey:@"savedData"];

//optional write to disk
[prefs synchronize];

/accessing objects
NSData *data = [prefs objectForKey:@"savedArray"];
NSInteger score = [prefs integerForKey:@"savedScore"];

//removing objects
[prefs removeObjectForKey:@"savedScore"];
[prefs removeObjectForKey:@"savedData"];

One of the much trickier subjects is storing data not in an NS-data type (for example an array of custom objects). The simple solution is to hack this data into a NSData object and store/retrieve this data instead. Simples.