0

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?

Justin Boo
  • 10,132
  • 8
  • 50
  • 71
user1253207
  • 45
  • 1
  • 1
  • 5

1 Answers1

0

Quick fix is to change:

int newTime = currentTime - 1;

into:

int newTime = (currentTime > 0) ? currentTime - 1 : 0;

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:

if ((currentTime > 0) && (newTime ==0)) {
    // optionally turn off timer
    fireZeroEvent ();
}

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.text without 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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
  • @user1253207: sorry, I mistyped - that first `:` should have been a `?` - try it again. – paxdiablo Apr 05 '12 at 13:41
  • @user1253207: I'll add that unless you have a specific reason to keep the timer going, you really should stop it. paxdiablo's code does not stop it; you need to add code for that yourself. – Peter Hosey Apr 06 '12 at 03:03