Question

I have a countdown timer in my game and I'm trying to figure out how to make it so that it shows two decimal places and records with 2 decimal places in my table. Right now it counts down as a whole number and records as a whole number. Any ideas?

-(void)updateTimerLabel{

     if(appDelegate.gameStateRunning == YES){

                            if(gameVarLevel==1){
       timeSeconds = 100;
       AllowResetTimer = NO;
       }
    timeSeconds--;
    timerLabel.text=[NSString stringWithFormat:@"Time: %d", timeSeconds];
}

    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateTimerLabel) userInfo:nil repeats:YES];
Was it helpful?

Solution

To have sub-second updates, the timer's interval needs to be < 1. But the precision of NSTimer is just around 50 ms, so scheduledTimerWithTimeInterval:0.01 will not work.

Moreover, the timer can be delayed by various activities, so using timeSeconds will lead to inaccurate timing. The usual way is compare the NSDate now with the date when the timer starts. However, as this code is for a game, the current approach may cause less frustration to players esp. if the program or background processes consumes lots of resources.


The first thing to do is to convert the countdownTimer to sub-second interval.

countdownTimer = [NSTimer scheduledTimerWithTimeInterval:0.67 target:self selector:@selector(updateTimerLabel) userInfo:nil repeats:YES];

Then, don't count down the time by seconds, but centiseconds:

if(appDelegate.gameStateRunning == YES){
   if(gameVarLevel==1){
      timeCentiseconds = 10000;
      AllowResetTimer = NO;
   }
}
timeCentiseconds -= 67;

Finally, divide by 100 in the output:

timerLabel.text=[NSString stringWithFormat:@"Time: %d.%02d", timeCentiseconds/100, timeCentiseconds%100];

Alternatively, use a double:

double timeSeconds;
...
if(appDelegate.gameStateRunning == YES){
   if(gameVarLevel==1){
      timeSeconds = 100;
      AllowResetTimer = NO;
   }
}
timeSeconds -= 0.67;
timerLabel.text=[NSString stringWithFormat:@"Time: %.2g", timeSeconds];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top