来自 Apple 文档:
定时器与运行循环一起工作。为了有效地使用计时器,
你应该知道运行循环是如何运作的——参见 NSRunLoop 和
线程编程指南。特别注意运行循环
保持对他们的计时器的强烈引用,所以你不必
添加计时器后,保持您自己对计时器的强引用
到一个运行循环。
您必须使 NSTimer 无效才能将其从运行循环中移除。
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSTimer_Class/
为了简化这个过程,你可以做的是创建两种方法,一种是创建和启动计时器,另一种是使时间无效。这些方法需要您将时间声明为 IVAR。
斯威夫特:
let timer = NSTimer(timeInterval: 1.0, target: self, selector: "incrementCompletedUnitCount:",
userInfo: nil, repeats: true)
progress.cancellationHandler = {
timer.invalidate()
}
progress.cancel()
目标-C
NSTimer * _studentTimer1;
-(void)startStudentTimer {
NSLog(@"***TIMER STARTED***");
_studentTimer1 = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(dowork) userInfo:nil repeats:TRUE];
}
-(void)invalidateStudentTimer1 {
[_studentTimer1 invalidate];
}
另外,为了安全起见,您可能希望将您的失效方法放在视图控制器的 dealloc 方法中。
您还可以考虑通过使用指向计时器的弱指针来采取额外的安全措施,如下所示:
NSTimer* __weak timer = [NSTimer scheduledTimerWithTimeInterval:30.0f target: self selector:@selector(tick) userInfo:nil repeats:YES];
或作为 IVAR:
NSTimer * __weak _studentTimer1;
不,至于你的最后一个问题,时间会一直停留在运行循环中,直到你明确地将其无效,这就是为什么你需要小心使用 NSTimer 并且应该尽可能安全地将其包装起来。