iPhone Development 101

iPhone 101

Code Tips






iPhone Development 101: Objective-C: Saving Data:
User Defaults

NSUserDefaults allows you to easily read and save data from anywhere in your app. The class provides methods for accessing common types such as floats, doubles, integers, and booleans; you can also store objects of type NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. For other object types, you'll have to use NSKeyedArchiver to store and retrieve data.

NSUserDefaults is appropriate for single data values, such as user preferences. If you need to store a large amount of similar data (records for a table, data on multiple users, etc.), then a sqlite database is more suitable.

To initialize the user defaults database, add the following to the applicationDidFinishLaunching method of your app delegate class:

// initialize defaults
NSString *dateKey    = @"dateKey";
NSDate *lastRead    = (NSDate *)[[NSUserDefaults standardUserDefaults] objectForKey:dateKey];
if (lastRead == nil)     // App first run: set up user defaults.
    NSDictionary *appDefaults  = [NSDictionary dictionaryWithObjectsAndKeys:[NSDate date], dateKey, nil];

    // do any other initialization you want to do here - e.g. the starting default values.    
    // [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"should_play_sounds"];
    // sync the defaults to disk
    [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
    [[NSUserDefaults standardUserDefaults] synchronize];
[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:dateKey];

To set a default value:

[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"is_running"];

To read a default value:

BOOL isRunning = [[NSUserDefaults standardUserDefaults] boolForKey:@"is_running"];

Use the appropriate getter/setter method to retrieve or set values:

Getters Setters
boolForKey: setBool:forKey:
doubleForKey: setDouble:forKey:
floatForKey: setFloat:forKey:
integerForKey: setInteger:forKey:
objectForKey: setObject:forKey:
arrayForKey: setObject:forKey:
dataForKey: setObject:forKey:
dictionaryForKey: setObject:forKey:
stringArrayForKey: setObject:forKey:
stringForKey: setObject:forKey:

Values returned from NSUserDefaults are immutable, even if you set a mutable object as the value. For example, if you assign a NSMutableArray to a key, you'll get back an NSArray when you retrieve it.

Additional References