In this tutorial, I will be showing you how you can save and retrieve different types of data using the NSUserDefaults object. Saving this way is great for when you want to save small amounts of data such as High Scores, Login Information, and program state.
Saving to the NSUserDefaults is great because it does not require any special database knowledge. So if you don’t want/have an SQLite3 database for your app, this would be the way to go.
In this tutorial, I do the following things:
Start With A View Based Application
This is done so we can start with a blank view. Since we won’t require any special functionality from our User Interface, this will be perfect.
Set Up IBOutles And An IBAction
We need to set up an IBOutlet for the UILabel and UITextField so that we can interact with the interface in code. The IBAction (updatePrefs) gets connected to our UIButton that we will add to the Interface. So when the user presses the button, this method will get called and save their data.
Create The Interface In Interface Builder
The interface for this application is pretty simple. It only requires a UILabel, UIButton, and a UITextField. Drag each of these components on to your View.
Connect The UI Components To Your Outlets/Action
If you are unfamiliar with what is happening here, read the tutorial Connecting Code To An Interface Builder View. We are simply making the connections between our UIComponents to the code. This will allow us to interact with them.
Implement The UpdatePrefs Method
This is where the NSUserDefaults actually get saved. In this method we perform the following tasks:
- Get reference to the NSUserDefaults object – This is done so we can call methods on it to save our data
- call the setObject forKey method – This allows us to save a string for a given key. The key is just a string value that we will use to look up our data.
- calling the resignFirstResponder method on the UITextField to hide the keyboard when the button (or return) is pressed
- Update the message text in the label to read “Application Preferences Saved” to notify the user that their preferences have been saved.
Implement The ViewDidLoad Method
We simply start by uncommenting this method. It gets called after the view loads (all components have been loaded and drawn). What we want to do in this method is to retrieve the saved NSUserDefault with the key @”greeting”. This will get the saved name that the user specified. If this variable is set to nil, then this is the first time the application has been run (or the user never saved their name).
Here are the steps that are taken in this method:
- Get a Handle to the NSUserDefaults object
- Retrieve the saved username by calling the getObject method and passing in the key @”greeting”
- Check if the saved username is nil – If so, display the default welcome message (Welcome guest)
- If the username is not nil, construct a new string with it using the initWithFormat constructor. This will allow us to append the username on to the message “Welcome”. initWithFormat takes 1 or more args. The first is the format of the string. In our case its @”Welcome %@!”. This is saying replace the “%@” with a string (which is the next parameter). If you have ever written in C, this is essetially the sprintf method.
- Once this string is build, we assign it to name.text to update the label
Here is a quick reference for some of the things you can do with NSUserDefaults
Saving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];
// saving an NSInteger
[prefs setInteger:42 forKey:@"integerKey"];
// saving a Double
[prefs setDouble:3.1415 forKey:@"doubleKey"];
// saving a Float
[prefs setFloat:1.2345678 forKey:@"floatKey"];
// This is suggested to synch prefs, but is not needed (I didn't put it in my tut)
[prefs synchronize];
Retrieving
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];
// getting an NSInteger
NSInteger myInt = [prefs integerForKey:@"integerKey"];
// getting an Float
float myFloat = [prefs floatForKey:@"floatKey"];
If you have any questions or comments, feel free to leave them in the comments section of this post, or post them in the forum. Also be sure and subscribe to the RSS Feed as I will be adding tutorials often. You can also download the sample code here. Happy iCoding!



90 Comments
I’m new to iPhone developing, and i have been checking out some of the tutorials you’ve written. Great material, very helpful!
However, after trying this one (and double-checking i followed all the steps correctly, i haven’t been able to get it running. I build it without errors, but when the iphone simulator tries to run it, the screen appears black for a few seconds and then the application quits with the message “terminate due to uncaught exception”. Any idea of what is going on here?
Thank you!
I’m new to iPhone developing, and i have been checking out some of the tutorials you’ve written. Great material, very helpful!
However, after trying this one (and double-checking i followed all the steps correctly), i haven’t been able to get it running. I build it without errors, but when the iphone simulator tries to run it, the screen appears black for a few seconds and then the application quits with the message “terminate due to uncaught exception”. Any idea of what is going on here?
Thank you!
Related question,
Is it possible to access global settings. For e.g: current ringtone, ring volume, etc..
Great tutorial…Assistance will be GREATLY appreciated re the following:
I am trying to read / write floating point GPS golf data to 1) “data.plist” via dictionary plistDict. Testing with “defaults” works correct but not with a data.plist XML list.
No problem with “defaults”:
Writing:
[defaults setFloat:loc.latitude forKey:keyLat];
[defaults setFloat:loc.longitude forKey:keyLong];
and then reading:
float HoleLat = [defaults floatForKey:@"Hole1Lat"];
float HoleLong = [defaults floatForKey:@"Hole1Long"];
However when writing:
[plistDict setObject:[NSNumber numberWithFloat:loc.latitude] forKey:keyLat];
[plistDict setObject:[NSNumber numberWithFloat:loc.longitude] forKey:keyLong];
is OK, but reading reading gives warning with:
float HoleLong = [plistDict floatForKey:keyLong];
float HoleLat = [plistDict floatForKey:keyLat];
\Warning is:
Warning: NSDictionary may not respond to -floatForKey. Incompatobel types in initialization.
I cannot get to read data back from the data.plist ! Please help !
Rgds Helmi
How would I use these methods to keep count of how many times a button was pushed in an app? The counter would start at 0 and go up to 999,999,999.
Thanks!
Hi Brandon,
How do you encrypt a password before saving it in NSUserDefaults?
Could you point me to the right direction or some links on how to implement this?
Thanks,
Wilbert
Is it possible to use these NSUserDefaults to save objects in an NSArray and display them on different views, connected through a UITableView?
Thanks for this wonderful and easy tutorial.
can brandon or anyone else explain or point me to another source on how i would modify this code so that i can save the index of an array when someone exits out of my app and loads the data from that index?
“if(messageName == nil)” should really be
“if(messageName == nil || [messageName isEqualToString: @""])” to keep the app from saying “Welcome, !”
how do i save the state of mw web pabe viewer
how do i save app state of a ui webview
Perfect tutorial. Was working for an hour to get this to function. After watching your tutorial it all made sense and I had it working in minutes.
Cheers
thanks, this works like a charme, i have on question, is it possible to clear this memory and start over?
Jeffrey
Thanks for the great post.
@Jeffrey, in the iphone simulator on the toolbar under iphone simulator is: reset content and setting… give that a shot
Hey man, the xcode project download is missing.
Nick
Great!
i was searching for this!!!!!!!!!!!!
it would be more better if u update it for savings the values in arrays.
Great work!!!
icodeblog is doing the superb job.
Thanx icode
Short and simple, exactly what I was looking for.
Thanks!
Thank you for posting this. Very usefull.
Hello… for some reason the Vid wont play.
Well, Crud after i posted this, it started playing. sorry
ZipFile wont download, says it isn’t there. The zip that has the code in it. I cannot get greeting.text to work. i get an error. says greeting undeclared.
ok, my bad again…
i named my lable lblGreeting so i didnt have an object greeting.
if (greetingName == nil) {
lblGreeting.text = @”Welcome Guest!”;
}
Thanks.
Hi
it’s really clear and neat tutorial, thanks brandon!
Btw, i wonder if it can do the same to save a photo, and use it as wallpaper, coz i m searching the save photo tutorial and no luck, hope u can help.
thanks a lot man!
Great! clear tutorial!
how i make it with views?
zipfile wont download, link broke
Great job on the demo! Clear & concise… thanks so much.
Brandon, you’re the best
you’re stuff are detailed, but not overcomplicated, like them very much. I like more the text tuts, but anyway you do great job on everything.
I laughed like crazy on the article about the iTunes’ iTennis … ‘the 12 year olds strike back’, lol but I’m sure you’ll be the star in ‘The return of the iCoders”
)
However, thumbs up man!
Marin
I would like to know what method do you use when you want to save the game object. Example you have one class then you create an object. Are you using setObject?
How could I go about using NSUserDefaults with Images? Please help and thanks in advance.
Brandon.
Thanks for the tutorial. Great information here.
I was just curious, is there a way to use NSUserDefaults to save the state of a UIButton? Basically, i’m working on an application where a button is disabled and displays an image with the user touches it. I just need to save this disabled state so that the next time the user launches the application, it will still be disabled and show the image.
- Thanks again
> Delegate Files – Each app has one delegate.
One?
Huh? We use many delegate files all through our apps.
If I put my LOAD code inside viewDidLoad, where do I put my SAVE code?
I like this tutorial. One question? I have used data to save and retrieve data using your tutorial and it works . How do I get another view in my app to do the same thing without affecting the nsdefaults setting in one specific view. Like I want to duplicated your example multiple times in different views in one app. I have tried adding another view and adding the similar code, even trying to change it so when you click the button for that one view it should save data entered for that view only? Can’t get it, some errors and other buttons to save text don’t work. Do you have any suggestions? Thank you.
hey babe, the sample code link is broken, please update.
thanks a lot
Hi this is a great tutorial, but i want to retrieve data from a file on a remote server (basically im going to update rugby scores on my own server then hopefully the iphone will load them automatically), any ideas on the remote bit ??? im new but not a noob
great tutorial though man Awesome.
Paul
Hey really great tutorial. I just want to let you know that the link to download the source is broken. I would really appreciate get the hand on it if possible. Thank you!
Just wanted to thank you for this tutorial. I used it to add save game functionality to my iPhone game, Battle for Vesta. I also posted my implementation on my blog if anyone is interested to see another example of NSUserDefaults in action.
It is worth mentioning that I found that I had to use the synchronize message to get the state to persist when I quit the application. Without it the state would only persist while the app was running.