views:

137

answers:

2

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!

+1  A: 

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.

TechZen
+2  A: 

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.

Steven Noyes
A good point that I will make sure to be more careful in the future. This is just a small test program though, so for the real thing I'll do better. Thank you!
Wayfarer
@Wayfarer -- Good habits are best enforced by ritualistic use. How much time did you waste on this problem that you could have saved by following the correct but tedious procedure?
TechZen