This is part of an ELC Tech Network

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:

Advertisement

  • 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!

This entry was posted in iPhone Programming Tutorials and tagged , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

90 Comments

  1. Carlos
    Posted March 23, 2009 at 10:26 am | Permalink

    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!

  2. Carlos
    Posted March 23, 2009 at 10:27 am | Permalink

    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!

  3. neha
    Posted March 29, 2009 at 4:17 am | Permalink

    Related question,
    Is it possible to access global settings. For e.g: current ringtone, ring volume, etc..

  4. Posted April 5, 2009 at 2:00 pm | Permalink

    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

  5. mesposito23
    Posted May 12, 2009 at 6:12 pm | Permalink

    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!

  6. Wilbert
    Posted May 18, 2009 at 11:58 pm | Permalink

    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

  7. Mike
    Posted June 9, 2009 at 10:47 am | Permalink

    Is it possible to use these NSUserDefaults to save objects in an NSArray and display them on different views, connected through a UITableView?

  8. Iya
    Posted June 12, 2009 at 2:20 pm | Permalink

    Thanks for this wonderful and easy tutorial.

  9. olivia
    Posted June 20, 2009 at 12:15 pm | Permalink

    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?

  10. Ben
    Posted June 22, 2009 at 7:07 pm | Permalink

    “if(messageName == nil)” should really be
    “if(messageName == nil || [messageName isEqualToString: @""])” to keep the app from saying “Welcome, !”

  11. mark funk
    Posted July 10, 2009 at 8:13 pm | Permalink

    how do i save the state of mw web pabe viewer

  12. mark funk
    Posted July 10, 2009 at 8:16 pm | Permalink

    how do i save app state of a ui webview

  13. Mike
    Posted July 27, 2009 at 9:12 am | Permalink

    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

  14. Posted August 16, 2009 at 2:22 am | Permalink

    thanks, this works like a charme, i have on question, is it possible to clear this memory and start over?

    Jeffrey

  15. Posted August 17, 2009 at 3:29 pm | Permalink

    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

  16. nick
    Posted August 30, 2009 at 6:11 am | Permalink

    Hey man, the xcode project download is missing.

    Nick

  17. Posted September 9, 2009 at 11:17 am | Permalink

    Great!
    i was searching for this!!!!!!!!!!!!

    it would be more better if u update it for savings the values in arrays.

  18. Arman
    Posted September 9, 2009 at 9:52 pm | Permalink

    Great work!!!

    icodeblog is doing the superb job.

    Thanx icode

  19. Gilad
    Posted September 14, 2009 at 11:03 am | Permalink

    Short and simple, exactly what I was looking for.

    Thanks!

  20. Claus Guttesen
    Posted October 7, 2009 at 4:25 pm | Permalink

    Thank you for posting this. Very usefull.

  21. Posted October 7, 2009 at 10:42 pm | Permalink

    Hello… for some reason the Vid wont play.

  22. Posted October 7, 2009 at 10:43 pm | Permalink

    Well, Crud after i posted this, it started playing. sorry

  23. Posted October 8, 2009 at 5:20 pm | Permalink

    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.

  24. Posted October 8, 2009 at 6:30 pm | Permalink

    ok, my bad again…

    i named my lable lblGreeting so i didnt have an object greeting.

    if (greetingName == nil) {
    lblGreeting.text = @”Welcome Guest!”;
    }

    Thanks.

  25. Nathan
    Posted October 10, 2009 at 9:54 pm | Permalink

    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!

  26. Luis
    Posted October 13, 2009 at 2:30 pm | Permalink

    Great! clear tutorial!

    how i make it with views?

  27. Posted October 16, 2009 at 7:44 pm | Permalink

    zipfile wont download, link broke

  28. dbarrett
    Posted October 26, 2009 at 9:24 pm | Permalink

    Great job on the demo! Clear & concise… thanks so much.

  29. Posted October 27, 2009 at 4:37 am | Permalink

    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

  30. Posted November 30, 2009 at 10:37 pm | Permalink

    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?

  31. Posted December 21, 2009 at 7:08 pm | Permalink

    How could I go about using NSUserDefaults with Images? Please help and thanks in advance.

  32. chris
    Posted January 19, 2010 at 5:04 pm | Permalink

    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

  33. Jill
    Posted February 7, 2010 at 12:50 am | Permalink

    > Delegate Files – Each app has one delegate.

    One?
    Huh? We use many delegate files all through our apps.

  34. Paula
    Posted February 7, 2010 at 7:29 pm | Permalink

    If I put my LOAD code inside viewDidLoad, where do I put my SAVE code?

  35. JJ2010
    Posted February 18, 2010 at 12:29 am | Permalink

    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.

  36. Ken Wong
    Posted February 23, 2010 at 9:07 pm | Permalink

    hey babe, the sample code link is broken, please update.

    thanks a lot

  37. Posted February 26, 2010 at 6:51 pm | Permalink

    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

  38. Posted February 27, 2010 at 9:20 pm | Permalink

    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!

  39. Posted March 8, 2010 at 11:17 am | Permalink

    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.

  40. Posted March 8, 2010 at 11:20 am | Permalink

    // This is suggested to synch prefs, but is not needed (I didn’t put it in my tut)
    [prefs synchronize];

    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.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">