User defaults, which have been referred to often already in this book (see especially Chapter 10 and Chapter 13), are intended as the persistent storage of the user’s preferences, as well as for maintaining state when your app quits so that you can restore the situation the next time the app launches. 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, 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 (
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 ...