How to save data in iOS

- by

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.



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.