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:
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.
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.
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.
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.
This is where the NSUserDefaults actually get saved. In this method we perform the following tasks:
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:
116 Comments
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?
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.
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
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 ) so that when the application gets loaded, the same array and therefore the same tableview is present? thanks!
Best iphone sdk tut I’ve seen. Thanks for sharing!
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
Nice tutorial. Definitely makes the daunting NSUserDefaults class very approachable. Thanks Man!
Good job! I like this tutorials especially with video.
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 !
Hi, Brandon, Nice video tutorial, which makes it easy to follow
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
@Yali,
Do you have the latest version of the SDK?
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!!
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!
@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…
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 ) so that when the application gets loaded, the same array and therefore the same tableview is present?
@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?
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.
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.
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.
@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…
I have to say, I definitely prefer the old style to the new video tutorials.
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.
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.
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?
Fantastic! I was looking for that!
Thank you!
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
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.
Thanks! There is so few information in the net..
Your topic was very useful for me.
Thanks for yet another brilliant tutorial Brandon.
Forget going to college, you should be working at Apple teaching people how to program the iPhone
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
@ter
Hahah you’re right. Consider it a “verbal typ-o”. Good catch… Thanks for reading
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 ?
Ciekawy post, dodalem twoj blog do ulubionych, bede tu teraz wpadal czesciej, pozdrawiam
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.
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
@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.
Great tutorial! You saved me a lot of time. Thank you very much. Greetings from Germany. Wolfgang.
Hi all,
i have face some problem for save the Data from using Sqlite. Anybody know tell me the answer.
Thanks for all.
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
hello
cn some one post a sample application of NSUrlConnection to download and post data to/from server
After a lot of developement testing… is there a way to “clear” all my defaults?
Or a way to “view” all my defaults?
I notice you “alloc” but never “release”.
When is it needed… or specifically avoided???
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?
// 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???
Is it possible to set initial default settings?
If the user launches the application for the first time and has not yet had the chance to set the preferences, they are nil.
I cannot find anything in the documentation about this?
Cheers
Graham
Personally, I like the video format with text a lot.
I quickly read the text before I watch the video and see if I understand what I’ll be doing. It’s a good knowledge check.
Then I watch the video, which is easy to follow and reinforces what I already remembered from reading the text.
Then I read the text again to make sure it all sank in.
Excellent job! I’m definitely getting the hang of iPhone development thanks to this site.
I am looking to have an app developed for my company. Are you interested in contract work?
Great Tutorial. I have a problem. Your tutorial works ok. But now i need to implement this with two xibs. i have the text field and the button in one xib. in another xib i have the label. i try all forms i could think but i could not make it work.
Anyone helps please?
thanks and sorry by my bad english
Brandon, outstanding tutorial! I am new to NSUserDefaults, but you explained this very well.
How would this change if I implemented a UITextView instead of a UITextField?
One Trackback
[...] Tutorial (link) [...]