尝试保存到 NSUserDefaults 时崩溃
当我尝试将当前级别计数保存到 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];
}
When I try to save the current level count to NSUserDefaults in the applicationWillTerminate
function it crashes on me. Why ?
----------------------- 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];
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
->
直接访问实例变量,然后为其分配一个自动释放的值。您需要使用点语法访问该属性才能正确保留它。另外,通过删除
@public
或将其更改为@private
将以下变量声明更改为私有,这样您就不会再遇到该问题了。You are accessing the instance variable directly by using
->
and then assigning it an autoreleased value. You need to access the property using dot syntax for it to properly be retained.Also change the following variable declarations to private by remove
@public
or changing it to@private
so you do not have that issue anymore.