I’ve created a countdown timer and it works great.. but when it reaches zero it continues counting down.. so it shows -1, -2, -3 etc. How do I prevent it from doing this?
This is my code from the implementation file..
@implementation ViewController
-(IBAction)start {
myTicker = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(showActivity) userInfo:nil repeats:YES];
}
-(IBAction)stop {
[myTicker invalidate];
}
-(IBAction)reset {
time.text = @"0";
}
-(void)showActivity {
int currentTime = [time.text intValue];
int newTime = currentTime -1;
time.text = [NSString stringWithFormat:@"%d", newTime];
}
I’m guessing that I’m missing some code somewhere?
Quick fix is to change:
into:
That will stop the countdown timer from going below zero. If that’s all you need, that should suffice.
It won’t turn off the timer or execute an action when it reaches zero. For that, you’ll need to add something like the following block after that line above:
and provide the
fireZeroEvent()function to do whatever you need to do.I say optionally turn off the timer since you may want to leave it running so you can restart the countdown by just be setting
time.textwithout have to recreate the timer.For that reason, the
fireZeroEvent()is only called on the transition from 1 to 0, not every time the timer fires after it reaches zero.