我有一个按时钟运行的重复计时器。在时钟运行期间,我调用 stopTimer 并且时钟应该停止。这在 iPhone 上 100% 有效,但在 iPad 上有时无法停止计时器。这发生在大约 50% 的时间里。NSLog 在 stop 方法中被调用。
这是我的计时器代码:
- (void)startSliderTimer
{
// Get start time
[self stopTimer];
startTime = [NSDate timeIntervalSinceReferenceDate] + kmaxTimePerSlider;
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01f target:self selector:@selector(updateClock) userInfo:nil repeats:YES];
}
- (void)updateClock
{
NSTimeInterval currentTimer = [NSDate timeIntervalSinceReferenceDate];
NSTimeInterval currentTimeLeft = startTime - currentTimer;
if (currentTimeLeft >= 0) {
int seconds = currentTimeLeft;
float milliseconds = currentTimeLeft - seconds;
int mill = milliseconds * 1000;
NSString* displayTime = [NSString stringWithFormat: @"%02d:%03d",seconds,mill];
timerLbl.text = displayTime;
} else {
[self tooSlow];
}
}
- (void) stopTimer
{
NSLog(@"%s",__FUNCTION__);
if (self.timer) {
NSLog(@"Stop Timer");
[self.timer invalidate];
self.timer = nil;
}
}
我刚刚尝试像这样运行计时器作为另一个问题/答案中的建议,但它仍然并不总是无效:
self.timer = [NSTimer timerWithTimeInterval:0.01f target:self selector:@selector(updateClock) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];