S. Naughton
S. Naughton

Reputation: 131

NSTimer - if statement not working within timer - CountDown Timer

I am working on a count down timer and am having trouble getting the if statement to stop the timer when the count is less that 0. Any guidance on solving this would be greatly appreciated. Thanks in advance for your help..

   -(void) startCountdown{
time = 90;
//NSLog[@"Time Left %d Seconds", time];
//This timer will call the function updateInterface every 1 second

   myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateInterface:) userInfo:nil repeats:YES];
}



-(void) updateInterface:(NSTimer*)theTimer{
if(time >= 0){
    time --;
    CountDownText.text = [NSString stringWithFormat:@"%d", time];
    NSLog(@"Time Left %d Seconds", time);
}
else{
    CountDownText.text =@"Times Up!";
    NSLog(@"Times Up!");
    // Timer gets killed and no longer calls updateInterface
    [myTimer invalidate];
}
}

Upvotes: 0

Views: 938

Answers (2)

tia
tia

Reputation: 9698

I tested your code and it worked perfectly and the timer stopped at -1. So my best guess is that time might be declared as unsigned value, so it never becomes less than zero.

Upvotes: 1

user467105
user467105

Reputation:

Looks like your countdown won't stop until it gets to -1 (instead of 0) because you're checking for greater-than-or-equal to zero and then decrementing (and then displaying).

Either decrement first and then check if time is greater-than zero:

-(void) updateInterface:(NSTimer*)theTimer{
    time --;
    if(time > 0){
        CountDownText.text = ...

or check if time is greater-than 1:

-(void) updateInterface:(NSTimer*)theTimer{
    if(time > 1){
        time --;
        CountDownText.text = ...

Upvotes: 0

Related Questions