Tag Archives: NSUserDefaults

How to load data in iOS

Here’s how you load data you’ve previously saved with NSUserDefaults. Since you only load data once I’d put this in the AppDelegate.m file (as applicationDidFinishLaunching) or in ViewDidLoad if you have a single view application:

The if/then statement here is used for when you haven’t yet got a saved value. Instead of a blank field you’ll end up with a pre-populated value.

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.