Why does my program crash when given negative values?
Alright, I am very confused, so I hope you friends can help me out. I'm working on a project using Cocos2D, the most recent version (.99 RC 1). I make some player objects and some buttons to change the object's life. But the weird thing is, the code crashes when I try to change their life by -5. Or any negative value for that matter, besides -1.
开发者_运维技巧Straight forward, but when the NSnumber is -5, it doesn't even get called, it crashes at the NSlog statement. So... what's up with that?
Solved it by retaining the variable better. Thank you!
OK. I will say this again. Accessors are your friends. Use them. Always. NOTE: Yes I know Apple recommends not using them in init and dealloc but in 15 years, this has NEVER once caused an issue for me and NOT using them has. As in this case. There are times when you do NOT want to use them, but those times are much less than the times you DO want to use them.)
In your buttonText method:
- (void)buttonText:(int)number
{
lifeChange = [NSNumber numberWithInt:number];
NSString *text = [[NSString alloc] initWithFormat:@"%d", number];
CCLabel *label = [CCLabel labelWithString:text fontName:@"Times New Roman" fontSize:20];
label.position = CGPointMake(35, 20);
[self addChild:label];
}
You should be doing a:
- (void)buttonText:(int)number
{
NSString *text = [[[NSString alloc] initWithFormat:@"%d", number] autorelease];
CCLabel *label = [CCLabel labelWithString:text fontName:@"Times New Roman" fontSize:20];
[self setLifeChange:[NSNumber numberWithInt:number]];
label.position = CGPointMake(35, 20);
[self addChild:label];
}
Take a look at your code and understand how alloc/copy/retain need balanced with release/autorelease. At first glance, you are really messing up on the memory management.
Well, part of your problem is that you are not using the notation "self.lifeChange" anywhere which means that the NSNumber objects you assign to the lifeChange
property are never retained. This means the NSNumber object may die at random.
Change to self.lifeChange
and see if that helps.
精彩评论