Madhu Madhu - 13 days ago 5
iOS Question

nstimer count down not working as expected

I am using

nstimer
to show count down timer in a label. I am able to start the timer and show the count down in the label but the timer jumps to next second rather than showing every second. If the count down timer is set to 10 sec then it shows only 9,7,5,3,1 in the count down timer label.

Below is my code.

NSTimer *tktTimer;
int secondsLeft;


- (void)startTimer {
secondsLeft = 10;
tktTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateCountdown) userInfo:nil repeats: YES];
}

-(void) updateCountdown {
int hours, minutes, seconds;

secondsLeft--;
NSLog(@"secondsLeft %d",secondsLeft);//every time it is printing 9,7,5,3,1 but should print 9,8,7,6,5,4,3,2,1,0
hours = secondsLeft / 3600;
minutes = (secondsLeft % 3600) / 60;
seconds = (secondsLeft %3600) % 60;
countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];


if (--secondsLeft == 0) {
[tktTimer invalidate];
countDownlabel.text = @"Completed";
}


}


Any help will be really appreciated.

Answer

--secondsLeft updates the variable. To check if the next decrement will be 0, use if (secondsLeft - 1 == 0)

Each tick is decrementing the variable twice.

Additionally, this will trigger the "Completed" text on 1, not 0. Below is a better way to handle this:

-(void) updateCountdown {
    int hours, minutes, seconds;

    secondsLeft--;
    if (secondsLeft == 0) {
        [tktTimer invalidate];
        countDownlabel.text = @"Completed";
        return;
    }        
    NSLog(@"secondsLeft %d",secondsLeft);//every time it is printing 9,7,5,3,1 but should print 9,8,7,6,5,4,3,2,1,0
    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;
    countDownlabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];
}
Comments