Using NSUserDefaults
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.
Thanks, that was a great simple tutorial, just what I needed!
Hello,
can I use [prefs setBool:bFlag forKey:@"BoolFlagKey"];
instead of [prefs setObject:bFlag forKey:@"BoolFlagKey"];
thanx for the tutorial, by the way
what happens, if the key does not exist…………or how can I check for the first time, when data is not saved and I call the load at the time of application launching?????
Two flaws saving an int:
1. setInteger, not setObject
2. One colon, not two
// saving a int
[prefs setInteger:23 forKey:@"intVal"];
“Code examples” are always welcome… but you also need to tell *WHERE* this code is to be placed?
Where would I put my LOAD code to execute it when the user navigates to a certain view?
Where would I put my SAVE code when the user exits that view?
Thanks for the quick tutorial, it was exactly what I needed to help me understand how to use NSUserDefaults to store options or simple data that I needed to load when my app started.
Nice tutorial – thanks.
@Tim – goof fix.
@Susan – my strategy is to have an AppState object which contains the (very simple) date for state I need. All the controllers can access it when they need to. For the save, I saw it recommended to use a method something like onAppClosing. But since I only update the state in a couple of places, I put a save method in AppState and just call that as soon as the data is changed.
I’m putting the load in the init method for app state.
@Rana – from http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html
You can see the default values, e.g. 0 for int, nil for NSString.
I mean to say “@Tim, good fix” where’s the edit button (:
It will not save anything!!!
It will not save my integer!!!