Game Development Reference
In-Depth Information
@property (nonatomic, retain) NSDate* date;
@property (nonatomic) int score;
+(id)score:(int)aScore At:(NSDate*)aDate;
@end
As shown in Listing 3-14, we see that it defines two properties, date and score. There is also a utility
constructor for quickly creating a
Score
object with these two properties filled in. As mentioned, the
class
Score
must conform to the
NSCoding
protocol in order for our archiving process to work. Listing
3-15 shows the implementation of the
Score
class.
Listing 3-15. Score.m
Score* highscore = [[Score alloc] init];
[highscore setScore:aScore];
[highscore setDate:aDate];
return highscore;
- (void)encodeWithCoder:(NSCoder *)encoder{
[encoder encodeObject:date forKey:@"date"];
[encoder encodeInt:score forKey:@"score"];
}
- (id)initWithCoder:(NSCoder *)decoder{
date = [[decoder decodeObjectForKey:@"date"] retain];
score = [decoder decodeIntForKey:@"score"];
return self;
}
- (NSComparisonResult)compare:(id)otherObject {
Score* otherScore = (Score*)otherObject;
if (score > [otherScore score]){
return NSOrderedAscending;
} else if (score<[otherScore score]){
return NSOrderedDescending;
} else {
return NSOrderedSame;
}
}
@end
Listing 3-15 shows us a couple of things. We see that the implementation of
score:At:
simply
creates a new
Score
object and populates the properties. The task
compare:
is used by
Highscores
to sort the
Score
objects (see the task
addScore
from Listing 3-13). We also see the now familiar task
for archiving and unarchiving:
encodeWithCoder:
and
initWithCoder:
. In the case of the
Score
class,
we store the
NSDate date
, with the object methods of
NSCoder
. For the
int score
, we have to use