iPhone Programming Tutorial – Saving/Retrieving Data Using NSUserDefaults

    October 3rd, 2008 Posted by: - posted under:Tutorials

    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 as I will be adding tutorials often. You can also download the sample code here. Happy iCoding!