Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop and Reset NSTimer

Tags:

ios

nstimer

I have a simple timer using that is activated with a button is pushed. It runs from 60 to 0 no problem but what I want is to stop and reset the timer on push button. I have managed to stop it when the button is pressed using the code below but for some reason cannot get it to reset and stop at 60. This should be simple but it isn't working. Any suggestions?

Timer is set using simple Action

- (IBAction)timerStart:(id)sender {

if(!secondCounter == 0){
        [countdownTimer invalidate];
    }
    else {
           [self setTimer];
     }
}

CODE FOR TIMER

- (void)timerRun {
    secondCounter = secondCounter - 1;
    int minutes = secondCounter;

    NSString *timerOutput = [NSString stringWithFormat:@"%d", minutes ];
    countDownLabel.text = timerOutput;

    if(secondCounter == 0){
        [countdownTimer invalidate];
        countdownTimer = nil;
    }
}

- (void)setTimer {
    secondCounter = 60;
    countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerRun) userInfo:nil repeats:YES];

}
like image 971
memyselfandmyiphone Avatar asked Feb 15 '23 19:02

memyselfandmyiphone


1 Answers

You need to set the seconds down to 0, otherwise the you always invalidate your timer, but never start it again:

- (IBAction)timerStart:(id)sender {
    if(!secondCounter == 0) {
        [countdownTimer invalidate];
        secondCounter = 0;
    }
    else {
        [self setTimer];
    }
}
like image 128
Christian Avatar answered Feb 27 '23 11:02

Christian