objective-cioscocoa-touchcocos2d-iphonecclabelttf

CCLabelTTF SetString not Updating


I'm using a CCLabelTTF to show the score of the player on the screen. However, when I'm calling setString to update the score label, it doesn't update (so it always stays at 0).

Here's my code :

In Player.m, I initiate a new PlayerHUD object:

- (id) init{
    if (self = [super init]){
        playerHUD = [[PlayerHUD alloc] loadPlayerInterface];
        [self addChild:playerHUD z:UPLAYER_Z];
    }
    return self;
}

In PlayerHUD.m, I initiate the Score Label :

- (id) loadPlayerInterface{
    if (self = [super init]){
        score = 0;
        //Score Label
        lblScore = [CCLabelTTF labelWithString:[NSString stringWithFormat:@"%d", score] fontName:@"pixel" fontSize:24];
        [self addChild:lblScore z:1000];
    }
    return self;
}

Still in PlayerHUD.m, here's my update function :

- (void) updateScore:(NSInteger)_newscore{
    score = _newscore;
    [lblScore setString:[NSString stringWithFormat:@"%d", score]];
}

And, in Player.m, I call the update function here :

- (void) addScore{
    int scoreToAdd = 50

    score += scoreToAdd;

    NSLog(@"Score:%d", score);
    [playerHUD updateScore:score];
}

Solution

  • Ok, I've find what was wrong, and I thought I would post it here, if anyone ever encounter this:

    The problem was that, for a reason that I still ignore, I needed to set a @property and @synthesize for my playerHUD object because, after some operations, it was becoming nil, like @InderKumarRathore said. So setting a property and synthesize for it solved the problem and never get lost again!

    And after some research, I think that's because of some modifications between cocos2D v.0.98 (the one I used before) and cocos2D v1.0 (the one I use right now) about memory management!

    Anyway, thank you all for your support, much appreciated!