使用 UIButton 停止 NSTimer

Stopping NSTimer with UIButton

我已经实现了一些代码,允许用户使用 UIDatePicker 设置倒计时的时间限制,然后用户按下 "Start" 按钮,倒计时将打印到 UILabel 中。

我正在尝试找到停止计时器的方法。这是我目前启动计时器的代码:

@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;
}

然后当用户用户按下 "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];

}

最后,当用户按下 "Stop":

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

}

有什么想法吗?

您需要保留对 NSTimer 的引用作为 ivar:

@implementation P11DetailController
{
NSTimer *myTimer;
}

然后:

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

然后简单调用:

[myTimer invalidate];

将停止计时器。

这些都在 documentation 中,您应该先查阅。