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:

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

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