Search code examples
iphoneiosnstimer

NSTimer Restarting


I have CountDown timer like below:

- (void)updateCounterLabel:(NSTimer *)theTimer {
    if(secondsLeft > 0 ){

    secondsLeft -- ;
    hours = secondsLeft / 3600;
    minutes = (secondsLeft % 3600) / 60;
    seconds = (secondsLeft %3600) % 60;

    countDownLabel.text = [NSString stringWithFormat:@"%02d:%02d:%02d", hours, minutes, seconds];

}
else{
    secondsLeft = timeInterval;
}

-(void)countdownTimer   {
    if([timer isValid]){
        [timer invalidate];
        timer = nil;
    }       
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateCounterLabel:) userInfo:nil repeats:YES];
}

----My problem is that every time recall this timer it increments like this : secondLeft-3 , secondLeft -5 ,secondLeft - 7..................

Each time my view loads, i create a new timer, but the old ones still exist.in my timer's action method, i am decrementing an index variable that keeps track of the seconds, and each timer runs that method every time it fires. So, if i have three timers, the index will decrements by three each time.

For example:

First Load: 60, 59, 58...

Second Load: 60, 58, 56...

Third Load: 60, 57, 54...

Question : How can i restart or recreate a timer without above problem? somebody help me out pls.


Solution

  • The

    timer = [NSTimer scheduledTimerWithTimeInterval:...];
    

    call retains the target (the view controller) while the timer is running, so that the view controller is never deallocated and the timer continues to run even if the view controller is popped off the navigation stack or dismissed.

    Therefore, if the view is loaded again, you have two instances of the view controller and therefore two timers, which both decrement the same global variable secondsLeft.

    This hopefully explains why the value is decremented by two each second.

    As a solution, you can create the timer in viewWillAppear, and invalidate it in viewWillDisappear.