How to save data in iOS

There are several ways to save and retrieve data for persistent storage (i.e. when you close your app and open it again). This is the easiest one I can think of: NSUserDefaults.

Here’s an example that saves a text field from an IBOutlet. We’re saving both a string and an integer. We can use this in any IBAction like a “save button”, via the ViewDidUnload method in your View Controller, or via methods in your AppDelegate.m file:

    // let's save our data
    NSString *emailAddress = [emailEditor text];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:emailAddress forKey:@"emailAddress"];
    [defaults setInteger:number forKey:@"theNumberKey"];
    [defaults synchronize];

The important thing to notice is that [defaults synchronize]; does the actual saving. This is not needed when you load the data (see next post). You can save as many options as you like, just remember which keys you’ve used so that you can retrieve those values later.

You can save the following types of data:
NSData, NSString, NSNumber, NSDate, NSArray, and NSDictionary.

Leave a Reply