Chapter 17. Storing User Defaults

In This Chapter

Storing and retrieving user preferences in NSUserDefaults
Adding and configuring a settings bundle for your iPhone app

Some of the most common types of data you'll need to store are user defaults. These usually include user preferences, minor data, and so on. Cocoa has always had an excellent user defaults system available for developers on the desktop. With the introduction of the iPhone, Apple brought the user defaults API to Cocoa Touch as well.

The class used to store user defaults is NSUserDefaults. Using this class, you can not only read and write virtually any value to the user defaults system, but you can also store "default defaults," which are the defaults if the user hasn't set a value.

When you store values to NSUserDefaults, the values are serialized and stored in your application sandbox under the directory Library/Preferences, similar to OS X for the desktop.

Acquiring the NSUserDefaults Object

NSUserDefaults is a singleton. This means that an application contains a single instance of NSUserDefaults that is used by the entire application, no matter where it's accessed. The class provides a static accessor to initialize and retrieve the singleton object. The accessor for this is standardUserDefaults. Listing 17.1 shows how you access the user defaults singleton.

This is all you need to do to read the user defaults singleton. There is no need to read anything or, when you're done with the object, to save anything. The NSUserDefaults ...

Get Cocoa Touch™ for iPhone® OS 3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.