iOS engineer who likes clean, simple designs and sans-serif.


NSUserDefault Cheatsheet

Some notes on how to save, update and persist data using NSUserDefault.

// Access NSUserDefaults using arrayForKey
NSMutableArray *spaceObjectPropertyLists =
  [[[NSUserDefaults standardUserDefaults] arrayForKey:SPACE_OBJECTS_KEY] mutableCopy];

// If data doesn't exist, initialize it
if (!spaceObjectPropertyLists) spaceObjectPropertyLists = [[NSMutableArray alloc] init];

// Update data (In this case, add object to array)
[spaceObjectPropertyLists addObject:[self spaceObjectPropertyList:spaceObject]];

// Update NSUserDefaults using setObject
[[NSUserDefaults standardUserDefaults] setObject:spaceObjectPropertyLists forKey:SPACE_OBJECTS_KEY];

// Save using NSUserDefaults synchronize
[[NSUserDefaults standardUserDefaults] synchronize];

Leave a Comment