当我尝试将当前级别计数保存到applicationWillTerminate
函数中的NSUserDefaults时,它会崩溃。为什么?
----------------------- AppDelegate.m --------------------- -
- (void)applicationWillTerminate:(UIApplication *)application {
CCDirector *director = [CCDirector sharedDirector];
HelloWorldLayer *hWClass = [[HelloWorldLayer alloc]init];
NSNumber *lCount = [NSNumber numberWithInt:hWClass -> level];
hWClass -> lvlCount =[NSUserDefaults standardUserDefaults];
[hWClass -> lvlCount setObject:lCount forKey:@"levelCount"];
[[director openGLView] removeFromSuperview];
[viewController release];
[window release];
[director end];
}
----------------------- HelloWorldLayer.h --------------------- -
...{
@public
int level;
NSUserDefaults *lvlCount;
int health;
...
}
@property (nonatomic,retain) NSUserDefaults *lvlCount;
----------------------- HelloWorldLayer.m --------------------- -
NSNumber *currentLevel = [[NSUserDefaults standardUserDefaults] objectForKey:@"levelCount"];
if (currentLevel != nil){
int cLevel = [currentLevel integerValue];
[self generateLevelFromPlist:cLevel];
}else{
[self generateLevelFromPlist:1];
}
答案 0 :(得分:0)
您正在使用->
直接访问实例变量,然后为其分配一个自动释放的值。您需要使用点语法访问该属性才能正确保留它。
hWClass.lvlCount =[NSUserDefaults standardUserDefaults];
[hWClass.lvlCount setObject:lCount forKey:@"levelCount"];
还可以通过删除@public
或将其更改为@private
将以下变量声明更改为私有,以便您不再遇到该问题。
...{
@private
int level;
NSUserDefaults *lvlCount;
int health;
...
}