QuickTip: NSUserDefaults

Just about every app that I work on utilizes NSUserDefaults in one way or another. It is quick to implement and very easy to use.

First you need to create an NSUserDefaults variable:

NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

Next you will need to save something that can be accessed at another time. This is very easy, we will use set methods to set values for keys. The keys can be named whatever you like, I named mine based on what object type I’m saving for this demo. Here we will save quite a few different object types:

// NSString
[userDefaults setObject:@"Your text here" forKey:@"StringKey"];

// Float
[userDefaults setFloat:5.22 forKey:@"FloatKey"];

// Double
[userDefaults setDouble:6.1234 forKey:@"DoubleKey"];

// NSInteger
[userDefaults setInteger:7 forKey:@"IntegerKey"];

// Boolean
[userDefaults setBool:YES forKey:@"BooleanKey"];

 

After saving objects to your NSUserDefaults, you will want to run the the synchronize method.

[userDefaults synchronize];

 

Next up we will retrieve values for the keys we saved above. Here we will get the object type for the keys we specified above and assign it to a variable.

// NSString
NSString *myString = [userDefaults stringForKey:@"keyToLookupString"];

// Float
float myFloat = [userDefaults floatForKey:@"floatKey"];

// Double
double myDouble = [userDefaults doubleForKey:@"DoubleKey"];

// NSInteger
NSInteger myInteger = [userDefaults integerForKey:@"integerKey"];

// Boolean
BOOL myBoolean = [userDefaults boolForKey:@"BooleanKey"];

And that is it! Hope you enjoyed this Quick Tip.

Email

One thought on “QuickTip: NSUserDefaults

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>