User Defaults

User defaults (NSUserDefaults), which have often been referred to earlier in this book (see especially Chapter 10 and Chapter 13), are intended as the persistent storage of the user’s preferences. They are little more, really, than a special case of an NSDictionary property list file. You talk to the NSUserDefaults standardUserDefaults object much as if it were a dictionary; it has keys and values. And the only legal values are property list values (see the preceding section); thus, for example, to store a Person in user defaults, you’d have to archive it first to an NSData object. Unlike NSDictionary, NSUserDefaults provides convenience methods for converting between a simple data type such as a float or a BOOL and the object that is stored in the defaults (setFloat:forKey:, floatForKey:, and so forth). But the defaults themselves are still a dictionary.

Meanwhile, somewhere on disk, this dictionary is being saved for you automatically as a property list file — though you don’t concern yourself with that. You simply set or retrieve values from the dictionary by way of their keys, secure in the knowledge that the file is being read into memory or written to disk as needed. Your chief concern is to make sure that you’ve written everything needful into user defaults before your app terminates; as we saw in Chapter 11, in a multitasking world this will usually mean when the app delegate receives applicationDidEnterBackground: at the latest. If you’re worried that your ...

Get Programming iOS 6, 3rd Edition 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.