Skip to content

NSUserDefaults Example

February 12, 2011

NSUserDefaults is a quick and easy way to store small amounts of data for you app. In this example, I’m going to show you how to use NSUserDefaults to store and retrieve data.

Storing Data

// create a standardUserDefaults variable
NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];

// saving an NSString
[standardUserDefaults setObject:@"mystring" forKey:@"string"];

// saving an NSInteger
[standardUserDefaults setInteger:42 forKey:@"integer"];

// saving a Double
[standardUserDefaults setDouble:3.1415 forKey:@"double"];

// saving a Float
[standardUserDefaults setFloat:3.1415 forKey:@"float"];

// synchronize the settings
[standardUserDefaults synchronize];

Retrieving Data

// create a standardUserDefaults variable
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

// getting an NSString object
NSString *myString = [standardUserDefaults stringForKey:@"keyToLookupString"];

// getting an NSInteger object
NSInteger myInt = [standardUserDefaults integerForKey:@"integerKey"];

// getting an Float object
float myFloat = [standardUserDefaults floatForKey:@"floatKey"];
About these ads

From → iOS Development

Leave a Comment

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

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: