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.

107 Comments

  1. dpigera
    Posted July 22, 2010 at 10:50 pm | Permalink

    Great tutorial man.. Couldn’t be more concise :-)

  2. iphone
    Posted July 23, 2010 at 8:02 am | Permalink

    what if the key doesnot exists. mean lets suppose we have had not stored an integer with the key “myInt”. bt we try to get value of that integer by

    int i = [prefs integerForKey:@"myInt"];

    in this case what would be returned???

  3. vincefried
    Posted July 27, 2010 at 2:49 pm | Permalink

    Amazing tut! But that doesn’t work on iOS 4! Can you help me?

    • Adam
      Posted August 9, 2010 at 4:44 pm | Permalink

      @vincefried

      Agreed. If you run this on a physical device and shut off the iphone, when you turn the phone back on, the data is not saved.

      For example:
      Lets say I want to keep track of a high score.
      When the player achieves a high score (lets say 5), the high score will be saved in memory because of ios4 multitasking, but if you shut your phone off you lose your score.

      Does anyone know how to write/read data and store it so data will be saved when the app is truly exited (ie: phone is shut off)?

      • Posted August 19, 2010 at 11:24 am | Permalink

        The data still stays for me when I turn off my device, OS 4.0.0

        What I did, which this tutorial didn’t, was to also use [synchronize]; before loading the data.

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="">