objective-ccocos2d-iphonecocos2d-iphone-3

Replacing NSString with new string not working


I'm trying to replace a string every second by using a timer to update its value. Normally I can replace an NSString pretty easily by doing

myString = [CCLabelTTF labelWithString:varyingParameterLabelString fontName:@"Helvetica" fontSize:14];

for example, but for some reason it won't update my NSString's value. Below is what I'm trying to do.

@implementation Grid
{
    NSTimer *timeRemainingTimer;
    CCLabelTTF *_varyingParameterLabelValue;
}


-(void)setupLabels{
    int timeRemaining = 30;
    varyingParameterLabelValueString = [NSString stringWithFormat:@"%i", timeRemaining];
    timeRemainingTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(decreaseTimeRemaining) userInfo:nil repeats:TRUE];
    _varyingParameterLabelValue = [CCLabelTTF labelWithString:varyingParameterLabelValueString fontName:@"Helvetica" fontSize:20];
[self addChild:_varyingParameterLabelValue];
}


-(void)decreaseTimeRemaining{
    timeRemaining--;
    NSString *timeRemainingString = [NSString stringWithFormat:@"%i", timeRemaining];
    _varyingParameterLabelValue = [CCLabelTTF labelWithString:@"timeRemainingString" fontName:@"Helvetica" fontSize:20];
//Still reads 30 after this runs
}

If I literally just copy and paste the last line of my timer method into the setupLabels method, it changes the string like normal, but inside of the timer method it doesn't do anything. I have logged to make sure the timer is running, and it definitely is. Thanks for the help!


Solution

  • In decreaseTimeRemaining you create a local variable called timeRemainingString, but then you never use it to update the label. Also, you are creating a whole new label instead of updating the existing one.

    -(void)decreaseTimeRemaining{
        timeRemaining--;
        NSString *timeRemainingString = [NSString stringWithFormat:@"%i", timeRemaining];
        [_varyingParameterLabelValue setString:timeRemainingString];
    }