我的应用程序运行良好,直到我停止它并重新启动 - 于是存档文件 - highScores.archive 存在。然后,应用程序停止编码 - 我在第一行得到一个 EXC_BAD_ACCESS(很长一段时间,直到我到达我正在编码的日期对象才发生。
我的猜测是我需要在几个地方放置一个保留,但我不知道在哪里。
编码:
FlipHighScores.h
...
@interface FlipHighScores : NSObject <NSCoding> {
//NSString *themeChosen;
NSInteger newHighScore;
NSInteger newScoreStartLevel;
NSInteger newScoreFinishLevel;
NSDate *scoreDateCreated;}
@property (copy, nonatomic) NSString *themeChosen;
@property (nonatomic) NSInteger highScore;
@property (nonatomic) NSInteger scoreStartLevel;
@property (nonatomic) NSInteger scoreFinishLevel;
@property (nonatomic, readonly, strong) NSDate *scoreDateCreated;
...
FlipHighScores.m ...
@synthesize themeChosen = _themeChosen;
@synthesize highScore = _highScore;
@synthesize scoreStartLevel = _scoreStartLevel;
@synthesize scoreFinishLevel = _scoreFinishLevel;
@synthesize scoreDateCreated = _scoreDateCreated;
...
-(void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:_themeChosen forKey:@"_themeChosen"];
NSLog(@"Theme Chosen is %@", _themeChosen);
[aCoder encodeInt:_highScore forKey:@"_highScore"];
[aCoder encodeInt:_scoreStartLevel forKey:@"_scoreStartLevel"];
[aCoder encodeInt:_scoreFinishLevel forKey:@"_scoreFinishLevel"];
NSLog(@"Date Created in encodeWithCoder is %@", _scoreDateCreated);
[aCoder encodeObject:_scoreDateCreated forKey:@"_scoreDateCreated"];}
-(id)initWithCoder:(NSCoder *)aDecoder {
if (self) {
_themeChosen = [aDecoder decodeObjectForKey:@"_themeChosen"];
_highScore = [aDecoder decodeIntForKey:@"_highScore"];
_scoreStartLevel = [aDecoder decodeIntForKey:@"_scoreStartLevel"];
_scoreFinishLevel = [aDecoder decodeIntForKey:@"_scoreFinishLevel"];
_scoreDateCreated = [aDecoder decodeObjectForKey:@"_scoreDateCreated"];
}
return self;}
-(NSString *)description {
NSDate *date = _scoreDateCreated;
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
NSString *dateString = [dateFormatter stringFromDate:date];
//NSLog(@"dateString from description is %@", dateString);
NSString *descriptionString = [[NSString alloc] initWithFormat:@"%d %@ S:%d F:%d D:%@", _highScore, _themeChosen, _scoreStartLevel, _scoreFinishLevel, dateString];
return descriptionString:}
我发现令人困惑的是,如果我删除保存文件 - highScores.archive 并运行该应用程序,它可以毫无问题地运行。我停止并终止应用程序,然后重新启动它 - 第一次编码称为崩溃。
在我对 themeChosen 对象进行编码的那一行。我已经阅读了一些关于通过“保留”或更改为 . 格式(为什么会有帮助,我不太明白)。但这是编码。解码可能是下一个问题......
我没有在这个项目上使用 ARC。也许当我从头开始重建整个事情时......
哦,我忘了提到在我添加跟踪主题变量之前,一切都运行顺利,直到我测试过。然后事情变得有点不对劲,就像这里提到的那样。