Using NSUserDefaults

August 20, 2008    Programming Snippets

This will go over a quick run through of using NSUserDefaults. This is the class to use to save user preferences for example. It is pretty straight forward.

Saving Data

This is how you save data.

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving a string
[prefs setObject:@"test" forKey:@"stringVal"];
// saving a int
[prefs setObject::23 forKey:@"intVal"];
// saving it all
[prefs synchronize];

Loading Data

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting the string
stringVal = [prefs stringForKey:@"stringVal"];
// getting the int
intVal = [prefs integerForKey:@"intVal"];

That is it.. pretty simple.

comments powered by Disqus