iPhone Programming Tutorial - Saving/Retrieving Data Using NSUserDefaults
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!
- Posted on 3 Oct 2008 in iPhone Programming Tutorials
- Digg |
- Del.icio.us |
- Stumble |
45 Responses
Bart Says:
October 3rd, 2008 at 12:03 pm
Thanks for the tutorials
One question… if you are using initWithFormat, and not releasing it, aren’t you leaking memory? Wouldn’t [NSString stringWithFormat:...] be a better choice?
Brandon Says:
October 3rd, 2008 at 12:14 pm
Good catch, I should have released this, but I was overcome with laziness…lol I’ll be sure to include the release stuff in future tutorials. Thanks for pointing this out.
mark Says:
October 3rd, 2008 at 1:38 pm
These tutorials have been wonderful! Thanks!
Could you add screen shots to the text you’ve added to the videos? I prefer the written tutorials since I can code while scrolling through the text. (The videos are nice for an overview but following along with them while coding is difficult.) Adding screen shots to the written portion of the video tutorials would be the best of both worlds.
Thanks for putting all this together!
– mark
theluiz Says:
October 3rd, 2008 at 2:32 pm
hey!
thanks for the tutorial, and i just wanted to know how to tie this in with an array of objects? ( the one u wrote about here http://is.gd/3uOi ) so that when the application gets loaded, the same array and therefore the same tableview is present? thanks!
mek Says:
October 3rd, 2008 at 3:39 pm
Amazing Tutorial
Brandon, is it possible to do another Sqlite3 tutorial, but instead of a todo program, just a standard contacts type app, with the instruction on how to Sort them and do a table search on them
example:
Search
—————
A
……Adam
……Alex
B
……Bob
C
……Candy
and then when the click on the name, it opens another view that displays some of their contact information
thanks
cruffenach Says:
October 3rd, 2008 at 3:57 pm
Nice tutorial. Definitely makes the daunting NSUserDefaults class very approachable. Thanks Man!
Serge ostrowsky Says:
October 4th, 2008 at 4:13 am
Bravo Brandon !
@Mek:
I don’t think Brandon has the time to develop exactly the App you want…
With his tutorials, you now have all you need to write it yourself !
And you will be even more proud of the result !
happy hunting !
yali900@gmail.com Says:
October 5th, 2008 at 11:21 am
Hi, Brandon, Nice video tutorial, which makes it easy to follow
Yali Says:
October 5th, 2008 at 11:30 am
Hi, Brandon, I have some problems after following your video tutorials, please help me figure out what’s wrong.
1. it does not work, when I relaunch the app it still says welcome guest. when I debug it and add following statement following your statement: greeting.text = [[NSString alloc] initWithFormat:@”Welcome %@!”,greetName];
name.text=greetName;
the name field is populated with the name I input last time.
it means that the app did retrieve the name correctly, but the “[NSString alloc] initWithForma… ” did not do its job. Do you know why.
2. when I download your sample code and run, I got following compiling error:
Checking Dependencies
error: There is no SDK with specified name or path ‘Unknown Path’
error: There is no SDK with specified name or path ‘Unknown Path’
Build failed (1 error)
What could possibly the cause ?
Thanks
screem Says:
October 6th, 2008 at 6:45 am
Again a very nice clean tutorial that is very easy to follow. I really look forward to all your future tutorials.
I hope that this site gets more communal since the NDA has now lifted. Let all help this site rise to the top!!
bearc0025 Says:
October 6th, 2008 at 8:46 am
Awesome again! Thanks!
A couple shortcuts for anyone that doesn’t know them (and will love them).
1. cmd+alt/option+up arrow = toggle btwn .m and .h of a class
2. ctrl+/ = skip to next parameter in coding a message send (not sure if that’s the best way to describe it - for an example watch the video - about 2/3rds thru, Brandon calls prefs setObject:forKey - he clicks on the second parameter to highlight it and type over. ctrl+/ does that for you.
THANKS Brandon!
Brandon Says:
October 6th, 2008 at 10:46 am
@screem,
thanks for the support. I really do hope to establish a great development community here. It seems that many sites are trying to be the official “iphone forums/community”…If iCodeBlog is to ever be like that, we need to get the forums a little more active. There is over 200 members so far, which is a really good start. Hopefully developers will start linking here more in their blog posts. This will really drive traffic and help the community.
@bearc
Those are great hints. Thank you for posting them. Would you mind posting them in the tips & tricks section of the forum. I’m sure they would get a lot of exposure there and help many people out. Thanks again…
theluiz Says:
October 6th, 2008 at 12:37 pm
hey!
thanks for the tutorial, and i just wanted to know how to tie this in with an array of objects? ( the one u wrote about here http://is.gd/3uOi ) so that when the application gets loaded, the same array and therefore the same tableview is present?
Brandon Says:
October 6th, 2008 at 6:53 pm
@theluiz,
I’m not sure this is the bes solution for storing arrays. If you want to store arrays, I would recommend using a SQLite3 database.
You could “ghetto rig” this by doing something like
*This is just pseudocode
for(i = 0 to array.length)
key = “arrayKey” . i
[prefs setObject:array[i] forKey:key];
end
Then you must also store the length of the array…
[prefs setInteger:array.length forKey:@"arrayLength"];
Does that make sense?
Yali Says:
October 6th, 2008 at 7:43 pm
Hi, Brandon, I think I have the latest SDK. I downloaded sdk on July 15. I ‘m wondering if others have the same problem as I do with problem 1:
1. it does not work, when I relaunch the app it still says welcome guest. when I debug it and add following statement following your statement: greeting.text = [[NSString alloc] initWithFormat:@”Welcome %@!”,greetName];
name.text=greetName;
the name field is populated with the name I input last time.
it means that the app did retrieve the name correctly, but the “[NSString alloc] initWithForma… ” did not do its job. Do you know why.
David Field Says:
October 7th, 2008 at 12:30 am
Will you be able to redo the last two tutorials (the video ones) in the same writen format as the previous ones - it is much easier to study from. The video is still though a great help.
David Field Says:
October 7th, 2008 at 12:33 am
One concept which is still not clear to me is how these files relate to each other:
* ‘File’s Owner’ in the .xib file
* Delegate files
* Controller files
If you can clarify the roles and relationships of these files it would be a great help. And thank you very much for the tutorials, it is the best stuff out there.
Brandon Says:
October 7th, 2008 at 8:41 am
@David,
I don’t have much time to re-do the video tutorials as text. I decided to do video as it provides a much better visual aid than text. I do try to provide some supplemental text explaining why each step is necessary under the video.
Delegate Files - Each app has one delegate. The delegate is where the app begins execution. If you open up main.m, it calls you appDelegate to start execution.
Controller - These are usually viewControllers. They are for the purpose of interfacing your interface with your views.
File’s Owner - This is the bridge between your viewController and Interface Builder. It provides a way for us to connect the view to the IBOutlets and IBActions in Interface Builder.
I hope these explanations are clear. Thanks for reading…
Ryan Brown Says:
October 8th, 2008 at 4:05 pm
I have to say, I definitely prefer the old style to the new video tutorials.
Marco from Ecuador Says:
October 8th, 2008 at 6:56 pm
Hi. I was just wondering if anybody has the programming code to create a simple ebook…. I would like to share some texts but I am a newby in programming for the iphone.
Yali Says:
October 8th, 2008 at 11:29 pm
I like the video tutorial much more than old style. It is straight forward and easy to understand what need to be done rather than trying to understand what to be done and how it is done through reading.
Brendan Says:
October 9th, 2008 at 5:32 pm
For some reason the defaults for my App don’t load on first launch. They will load if I visit Settings>My App Settings, then re-launch my App.
Any ideas? I tried invoking updatePrefs in viewDidLoad, but that only updated the Switches and not the TextFields.
I’m really pulling my hair out, since it seems like the whole viewDidLoad should load the DefaultValues.
Help?
SM Says:
October 10th, 2008 at 6:50 pm
This might sound very silly question. However I see a big Q with a question mark on it where the video should be.
What software am i missing?
Please help
Brandon Says:
October 10th, 2008 at 10:34 pm
It’s not a silly question. It means you need to get the latest version of quicktime. All of my tutorials are .mov so they require quicktime to play.
ahot Says:
October 14th, 2008 at 1:10 am
Thanks! There is so few information in the net..
Your topic was very useful for me.
Scott Says:
October 16th, 2008 at 6:03 am
Thanks for yet another brilliant tutorial Brandon.
Forget going to college, you should be working at Apple teaching people how to program the iPhone
ter Says:
October 16th, 2008 at 8:50 am
fantastic tutorial. very concise & very well paced.
one question though :
initWithFormat:@”Welcome %@!” ,greetName];
% AT !
you said “% Ampersand ” in the audio. isn’t it %@, not %&?
thanks again for the tutorials.
~t
Brandon Says:
October 16th, 2008 at 10:11 am
@ter
Hahah you’re right. Consider it a “verbal typ-o”. Good catch… Thanks for reading
John Says:
October 22nd, 2008 at 12:08 pm
Hi Brandon,
I’ve used this tutorial as the basis for adding a settings view to my app which works well. Basically the user needs to choose from a set of values similar to a “select” in HTML so I use a UIPIckerView.
I’ve started to move most of my options to settings.bundle but and have most things working except for getting the selected value and title back from a “PSMultiValueSpecifier”.
Any suggestions ?
Bukmacher Says:
October 28th, 2008 at 12:26 pm
Ciekawy post, dodalem twoj blog do ulubionych, bede tu teraz wpadal czesciej, pozdrawiam
Peter Says:
November 11th, 2008 at 8:15 am
Great tutorial. I have a question with regards IBOutlets, @properties, @synthesize. Is it really necessary to add properties for IBOutlets. Seems to work without these.
Using latest version of SDK.
Regards Peter.
chris Says:
November 11th, 2008 at 12:51 pm
Thank you for the great tutorials! I’m completely new to coding so I’m slowly making my way through them all.
Question about this one:
Why is it after I enter my name and click done the app goes directly to “Your preferences have been saved!” without having pressing the “Update Preferences” button?
I thought maybe i had screwed something up, but it does the same thing when i compile your source as well.
Am I missing something?
-chris
Brandon Says:
November 11th, 2008 at 2:04 pm
@chris,
This is the way I set it up. When the “Return” button is pressed on the keyboard, it calls the same function that gets called when you tap the “Update Preferences” button.
If you don’t want this functionality, skip the step where i make this connection in Interface Builder.
Wolfgang Says:
November 20th, 2008 at 5:23 pm
Great tutorial! You saved me a lot of time. Thank you very much. Greetings from Germany. Wolfgang.
gopi Says:
November 24th, 2008 at 6:58 am
Hi all,
i have face some problem for save the Data from using Sqlite. Anybody know tell me the answer.
Thanks for all.
Tarun sharma Says:
December 9th, 2008 at 12:20 am
hello brandon
i hav just started working on i phone application and found this site very usefull .i m really very thankfull to u and will try my best to provide the resourecs to this site.thanks again buddy
Tarun sharma Says:
December 15th, 2008 at 2:11 am
hello
cn some one post a sample application of NSUrlConnection to download and post data to/from server
susan@codeblog.com Says:
December 31st, 2008 at 10:38 pm
After a lot of developement testing… is there a way to “clear” all my defaults?
Or a way to “view” all my defaults?
Donna Says:
December 31st, 2008 at 10:50 pm
I notice you “alloc” but never “release”.
When is it needed… or specifically avoided???
Tammie Says:
January 1st, 2009 at 10:09 pm
Is there a way to save my prefs if the user just hits HOME and exits?
Maybe put code in some kind of DidViewUnload function?
Tammie Says:
January 1st, 2009 at 10:48 pm
// This is suggested to synch prefs, but is not needed (I didn’t put it in my tut)
[prefs synchronize];
It’s not needed? But it’s “suggested” that I DO use it?
When should I add it… or delete it?
What does it even do? It “syncs” my prefs to what???




