Graphics Programs Reference
In-Depth Information
Using NSUserDefaults
What we need to do now is store a value to specify the map type that the user last selected
so that the chosen type will automatically be displayed when the user launches the applica-
tion again. This value will be stored in an instance of NSUserDefaults .
Every application has an instance of NSUserDefaults that it can access by sending the
class message standardUserDefaults to the NSUserDefaults class. This in-
stance of NSUserDefaults is like an NSMutableDictionary ; you can access ob-
jects in it using a key. It is also automatically read from disk when the application first ac-
cesses it and written to disk when it is modified.
The keys of an NSUserDefaults are always of type NSString . A key identifies a
preference. An object represents the value of a preference. These objects must be property
list serializable or primitives. For example, if you created a key “Text Size” and assigned
the integer 16, it would mean the user's preferred text size is 16 points.
But that “Text Size” key is a completely hypothetical example. There isn't a built-in key
that magically resizes all of your text. In fact, there are no built-in keys at all. Instead, you
create your own keys specific to your application and give them values that mean
something to your application.
The key you will create for Whereami is a string, and it will be used for both reading and
setting the value. You will define it as a static variable so that you can pass a variable as the
key instead of a hard-coded string. (If you mistype a variable name, the compiler will give
you an error. But it can't help if you've mistyped a string.)
At the top of WhereamiViewController.m , declare a new static variable to hold the
preference name for the map type.
NSString * const WhereamiMapTypePrefKey = @"WhereamiMapTypePrefKey";
@implementation WhereamiViewController
Notice that the key is the name of the application, the name of the preference, and the
words PrefKey . This is the typical pattern for naming preference keys.
To add or change the value of a preference in an NSUserDefaults , you use setOb-
ject:forKey: just like you would with an NSMutableDictionary . In addition,
NSUserDefaults has some convenience methods for putting primitives into preferen-
ces, like setInteger:forKey: .
Search WWH ::




Custom Search