Game Development Reference
In-Depth Information
the
sharedGameState
method.
Listing 7-12
.
The musicVolume property setter and getter methods
static NSString* KeyForMusicVolume = @"musicVolume";
-(void) setMusicVolume:(CGFloat)volume
{
[[NSUserDefaults standardUserDefaults] setDouble:volume
forKey:KeyForMusicVolume];
}
-(CGFloat) musicVolume
{
NSNumber* number = [[NSUserDefaults
standardUserDefaults]
objectForKey:KeyForMusicVolume];
return (number ? number.doubleValue : 1.0);
}
The
NSUserDefaults
key is declared as a
static NSString*
variable so that you
don't have to write the string twice. If you ever made a typo writing the same thing twice
over, you'll understand the value of declaring frequently used strings as
static
vari-
ables.
Property setter and getter methods follow a consistent naming scheme. The getter has the
same name as the property; the setter prefixes the property name with
set
, and the prop-
erty's first letter is capitalized.
NSUserDefaults
is the class that persists any integral data type and so-called property
list objects:
NSData
,
NSString
,
NSNumber
,
NSDate
,
NSArray
, or
NSDiction-
ary
. So it won't save your custom class just like that. But you can save individual proper-
ties of your classes, like the volumes here.
The
standardUserDefaults
is a singleton accessor just like
sharedGameState
.
The
setDouble:forKey:
method stores a value of type
double
for the given key,
which must be an
NSString*
object. The same key is then used in
objectForKey:
to receive the
NSNumber
object associated with that key.
NSUserDefaults
will al-
ways return integral data types wrapped in
NSNumber
objects so that it can return
nil
to
signal that there's no entry for the given key, which will be the case when you first launch
the app.
Search WWH ::
Custom Search