Game Development Reference
In-Depth Information
Listing 3-17. CoinsGame.m (encodeWithCoder: and initWithCoder:)
- (void)encodeWithCoder:(NSCoder *)encoder{
[encoder encodeObject:coins forKey:@"coins"];
[encoder encodeInt:remaingTurns forKey:@"remaingTurns"];
[encoder encodeInt:score forKey:@"score"];
[encoder encodeInt:colCount forKey:@"colCount"];
[encoder encodeInt:rowCount forKey:@"rowCount"];
}
- (id)initWithCoder:(NSCoder *)decoder{
coins = [[decoder decodeObjectForKey:@"coins"] retain];
remaingTurns = [decoder decodeIntForKey:@"remaingTurns"];
score = [decoder decodeIntForKey:@"score"];
colCount = [decoder decodeIntForKey:@"colCount"];
rowCount = [decoder decodeIntForKey:@"rowCount"];
return self;
}
In Listing 3-17, we see the task used by CoinsGame to support archiving and unarchiving. In each
task, a number of properties are encoded or decoded—nothing too surprising there, presumably. An
object can be archived at any point in the application life cycle, but there are special tasks that are
called when an application is either closing or terminating. These are the following:
- (void)applicationWillTerminate:(UIApplication *)application
- (void)applicationDidEnterBackground:(UIApplication *)application
The task applicationWillTerminate: is called just before the application is terminated. Its cousin
task applicationDidEnterBackground: is similar, but it is called when the application is sent to
the background. If your application supports background execution (the default in new projects),
the task applicationWillTerminate: will not be called; you must put your archiving logic in
applicationDidEnterBackground: . This is the case because a user can exit an application in the
background at any point; so it makes sense to have the bookkeeping taken care of beforehand,
while the application is fully active. There are a number of other life cycle tasks available to app
delegates. When you create a new project in Xcode, these tasks are automatically added to your
app delegate class with nice documentation.
Implementing Life Cycle Tasks
Because our application supports background execution, we put the archiving logic into the
applicationDidEnterBackground: task, as shown in Listing 3-18.
 
Search WWH ::




Custom Search