Graphics Programs Reference
In-Depth Information
Build and run
Whereami
and change the map type. Exit the application by pressing the
Home button and kill it from
Xcode
. Then, relaunch it, and the map will display the type
of map you previously selected.
When your application first launches, the value for the key
WhereamiMapTypePre-
fKey
does not exist, and it defaults to 0. For this application, that works fine, but some
preferences may need a temporary, non-zero default value (i.e., a “factory setting”) for the
application to run correctly. These temporary defaults are placed in the
registration do-
main
of
NSUserDefaults
. Any preferences set by the user are stored in a different do-
main, the
application domain
.
By default, the application domain is empty: there are no keys and no values. The first
time a user changes a setting, a value is added to the application domain for the specified
key. When you ask the
NSUserDefaults
for the value of a preference, it first looks in
the application domain. If there is a value for that key, then the user has set a preference,
and the
NSUserDefaults
returns that value. If not, the
NSUserDefaults
looks in
the registration domain and finds the temporary default.
The application domain is always saved to disk; that's why it remembers user preferences
on the next launch. The registration domain is not, and its values must be set every time
the application launches. To set the values of the registration domain, you create an
NSDictionary
with a key-value pair for each preference you plan on using in your ap-
plication. Then, you send the dictionary as an argument to the method
registerDe-
faults:
of
NSUserDefaults
.
Typically, you send the
registerDefaults:
message before any object is able to ac-
cess the instance of
NSUserDefaults
. This means before the instance of the applica-
tion delegate is created. What comes before the creation of the
WhereamiViewCon-
troller
? The creation of the
WhereamiViewController
class
. Like any object, a
class also must be initialized before it can receive messages. So, after a class is created but
before it receives its first message, it is sent the message
initialize
.
In
WhereamiViewController.m
, override the class method
initialize
to re-
gister defaults, including setting the map type preference to 1.
+ (void)initialize
{
NSDictionary *defaults = [NSDictionary
dictionaryWithObject:[NSNumber numberWithInt:1]
forKey:WhereamiMapTypePrefKey];
[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
}