Game Development Reference
In-Depth Information
special tasks, because an
int
is not an object.
NSCoder
provides a special task for primitive types. In
our case, we use
decodeInt:ForKey:
and
encodeInt:ForKey:
. There exists analog task for the other
primitive types, like
BOOL
,
float
,
double
, and so on.
We have looked at the implementation required by a class we wish to archive (and unarchive), but
we have not looked at how we actually unarchive an object from the user's preferences. Listing 3-16
shows how this is done in the class
HighscoreController
.
Listing 3-16. HighscoreController (viewDidLoad)
- (void)viewDidLoad
{
[super viewDidLoad];
[highscores release];
NSData* highscoresData = [[NSUserDefaults standardUserDefaults] dataForKey:KEY_HIGHSCORES];
if (highscoresData == nil){
highscores = [[[Highscores alloc] initWithDefaults] retain];
[self saveHighscores];
} else {
highscores = [[NSKeyedUnarchiver unarchiveObjectWithData: highscoresData] retain];
}
[self layoutScores:nil];
}
The
viewDidLoad
task from Listing 3-16 is called when a
HighscoreController
's view is loaded. In
this task, we want to prepare the
HighscoreController
for use. This means making sure
highscores
is in a usable and accurate state, and we want to lay out the current set of high scores in case this
view is displayed before a new
Score
is added. In order to retrieve the current high scores, we read
a
NSData
object from the
NSUserDefaults
object returned by the call to
standardUserDefaults
. If
the
NSData
object is
nil
, which will happen the first time you run the application, we initialize a new
Highscores
object and immediately save it. If the
NSData
object is not
nil
, we unarchive it with a call
to
NSKeyedUnarchiver
's task
unarchiveObjectWithData
and retain the results.
We have looked at how an object can be archived and unarchived in this section. We will now use
the same principles to show how we can archive and unarchive our game state.
Preserving Game State
With the advent of background execution on iOS devices, the importance of preserving game or
application state is a bit reduced. But a fully functional and user-friendly application should be able
to gracefully handle restoring state if the application is terminated. The steps required to preserve
state are really not that different from storing other types of data. This is a critical feature of many
applications.
The first thing we need to understand is when we should be trying to restore state or archive state.
Figure
3-11
is a flowchart describing our sample application's life cycle in terms of initialization.