【发布时间】:2012-04-29 21:06:38
【问题描述】:
我觉得我产生了幻觉。我正在尝试为我的 Concentration-lke 游戏添加一些持久性。我想跟踪高分。我今天让这个部分工作了一段时间,现在它已经全部消失了(我认为这是正确的 iOS 术语)。现在,我的 allHighScores NSMutablearray 突然变成了一个 CALayer。我正在使用 NSKeyed 归档。在 allHighScores 加载数据之前,我的文件中有一个断点。在单步执行应用程序时,allHighScores 作为 NSMutableArray 存在 - 然后,在下一步,它突然变成了 CA 层。嗯?
-(id)init
{
self = [super init];
if (self) {
NSString *path = [self flipScoreArchivePath];
NSLog(@"Path is %@", path);
allHighScores = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
if (!allHighScores) {
allHighScores = [[NSMutableArray alloc] init];
}
}
return self;
}
+(FlipHighScoreStore *)sharedStore {
static FlipHighScoreStore *sharedStore = nil;
if (!sharedStore) {
sharedStore = [[super allocWithZone:nil]init];
}
return sharedStore;
}
不知何故,调用 NSKeyedUnarchiver 将我的 allHighScores 从 NSMutableArray 更改为 CALayer。我很困惑。
我尝试在取消归档指令中添加保留,但这没有帮助。
这是我的编码/解码代码:
-(void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.themeChosen forKey:@"themeChosen"];
[aCoder encodeInt:self.highScore forKey:@"highScore"];
[aCoder encodeInt:self.scoreStartLevel forKey:@"scoreStartLevel"];
[aCoder encodeInt:self.scoreFinishLevel forKey:@"scoreFinishLevel"];
[aCoder encodeObject:scoreDateCreated forKey:@"scoreDateCreated"];}
-(id)initWithCoder:(NSCoder *)aDecoder {
if (self) {
self.themeChosen = [aDecoder decodeObjectForKey:@"themeChosen"];
self.highScore = [aDecoder decodeIntForKey:@"highScore"];
self.scoreStartLevel = [aDecoder decodeIntForKey:@"scoreStartLevel"];
self.scoreFinishLevel = [aDecoder decodeIntForKey:@"scoreFinishLevel"];
scoreDateCreated = [aDecoder decodeObjectForKey:@"scoreDateCreated"];
}
return self;}
更新:当“highscores.archive”文件已经存在并且再次调用保存时程序崩溃。我可以启动应用程序,查看高分 - 他们在那里并愉快地检索,但保存代码:
-(BOOL)saveHighScores {
NSString *path = [self flipScoreArchivePath];
return [NSKeyedArchiver archiveRootObject:allHighScores toFile:path];}
导致 EXC_BAD_ACCESS。路径是正确的,所以不知何故 allHighScores 不是。
【问题讨论】:
-
您能告诉我们您是如何在
FlipHighScore中实现NSCoding 协议的吗?或者任何类名? -
试试这个
NSLog(@"unarchived class %@",NSStringFromClass([allHighScores class]));并记下输出。 -
当一个对象神奇地转变为另一个对象时,这表明第一个对象被过度释放(或保留不足)并被释放,另一个对象被分配到它的位置。
-
是的,我正在使用 ARC。 - 我将添加一点编码!我在 allHighScores 未存档之前和之后登录 - 在我得到“unarchived class null”之前和在我得到“unarchived class CA Layer”之后。
-
为什么在
+ sharedStore中使用[super alloc]而不是[self alloc]?
标签: ios nskeyedarchiver