Game Development Reference
In-Depth Information
- (id)initWithCoder:(NSCoder *)decoder{
theScores = [[decoder decodeObjectForKey:@"theScores"] retain];
return self;
}
-(void)dealloc{
for (Score* score in theScores){
[score release];
}
[theScores release];
[super dealloc];
}
@end
The implementation of the class
Highscores
shown in Listing 3-13 is pretty compact. The task
initWithDefaults
initializes the
NSMutableArray theScore
and then fills
theScores
with ten new
Score
objects. The task
addScore:
adds a new
Score
object to the
theScores
, sorts it by the score
achieved by the player, and then removes any extra
Scores
. This may result in the
Score newScore
not actually being in the
NSMutableArray theScores
. However, it is implemented in this way so
the caller does not have to consider the fact that the
theScore
might not be high enough to be
considered an actual high score. The last two tasks,
encodeWithCoder:
and
initWithCoder:
,
are from the protocol
NSCoding
. These tasks describe how a
Highscores
object is archived and
unarchived. Note that the object passed to both of these arguments is of the same type:
NSCoder
.
The class
NSCoder
provides tasks for encoding and decoding values.
NSCoder
is very much like
other iOS classes in that it presents a map-like interface for reading and writing data. In the task
encodeWithCoder:
, we use the
NSCoder
task
encodeObject:forKey:
to write
theScore
object to
the encoder. We pass in a key value
NSString
that we will use in
initWithCoder:
to read the
theScores
back out when we unarchive this class. Also note that the object that is returned from the
decodeObjectForKey:
task is retained. This is done to make sure the object returned is not reclaimed
at some unspecified time.
When an
NSMutableArray
is encoded with an
NSCoder
, it knows to encode the elements in the array,
but those elements must know how to be encoded. Because
theScores
is an
NSMutableArray
filled
with
Score
objects, we have to tell the class
Score
how to encode and decode itself for this process
to work.
The Score Class
Score
objects represent a date and score value. We have seen how the class
Highscores
manages a
list of
Score
objects. Let's take a quick look at this simple class. Listing 3-14 shows the header of the
Score
class.
Listing 3-14. Score.h
#import<Foundation/Foundation.h>
@interface Score : NSObject <NSCoding>{
NSDate* date;
int score;
}