ios - NSTimer Press "Start"Again then Cannot "Stop"

标签 ios objective-c nstimer

一个奇怪的情况:

如果我一次又一次地启动我的计时器而不先停止它,它会越来越快。我猜是因为它现在启动了多个计时器?

然而,当我终于想阻止它时,它却无法停止……永远继续下去。

(也许出于设计考虑,我应该禁止用户再次按下开始,但我想知道这背后到底是什么以及为什么计时器无法停止。)

- (IBAction)Start:(id)sender {
    countInt = 0;
    self.Time.text = [NSString stringWithFormat:@"%i", countInt];
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(countTimer) userInfo:nil repeats:YES];
}

- (IBAction)Stop:(id)sender {
    [timer invalidate];
}

- (void) countTimer {
    countInt += 1;
    self.Time.text = [NSString stringWithFormat:@"%i", countInt];
}
@end

最佳答案

简单的解决方案是在start 方法的开头调用stop

注意在stop中你还应该设置timer = nil;

关于ios - NSTimer Press "Start"Again then Cannot "Stop",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37573784/

相关文章:

ios - 离开该 View 时暂停 NSTimer 并在返回时继续计数?

ios - RubyMotion 自定义 UITableViewCell 与 Nib

iphone - 如何将UIView的部分转换为UIImage并在imageView中显示

objective-c - 层支持/层托管 NSViews 的不稳定行为

iOS 自定义键盘扩展自动大写

ios - NSString解码

objective-c - 点击单元格内的按钮时更新 UITableViewCell 外观

objective-c - 以编程方式设置 NSIndexPath

ios - 更新在后台运行的标签的计时器

ios - 如何在 Swift 游戏中制作前台和后台 2-3 小时计时器?