Search code examples
iosobjective-cuibuttonnstimer

Stopping NSTimer with UIButton


I have implemented some code that allows a user to set a time limit to countdown from using UIDatePicker, the users then presses a "Start" button and the countdown is printed in to a UILabel.

I am trying to find a way to stop the timer. Here is the code I have so far that starts the timer:

@implementation P11DetailController
int afterRemainder;
int iRemainder;
NSTimeInterval countDownInterval;

- (void)updateCountDown{
afterRemainder --;

int hours = (int)(afterRemainder)/(60*60);
int mins = (int)(((int)afterRemainder/60) - (hours * 60));
int secs = (int)(((int)afterRemainder - (60 * mins) - ( 60*hours*60)));

NSString *displayText = [[NSString alloc] initWithFormat:@"%02u : %02u :
%02u", hours, mins, secs];

self.displayLabel.text = displayText;
}

then when the user user presses "start":

- (IBAction)startButton:(id)sender {
countDownInterval = (NSTimeInterval)_countdownTimer.countDownDuration;
iRemainder = countDownInterval;
afterRemainder = countDownInterval - iRemainder%60;
[NSTimer scheduledTimerWithTimeInterval:1 target:self 
selector:@selector(updateCountDown) userInfo:nil repeats:YES];

}

and finally, when the users presses "Stop":

- (IBAction)stopButton:(id)sender {
//not sure what to add here

}

any ideas?


Solution

  • You need to keep a reference to NSTimer as an ivar:

    @implementation P11DetailController
    {
    NSTimer *myTimer;
    }
    

    then:

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

    Then a simple call to:

    [myTimer invalidate];

    Will stop the timer.

    This is all in the documentation which you should consult first.