1

我有一个按时钟运行的重复计时器。在时钟运行期间,我调用 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];
4

2 回答 2

1

创建计时器而不使用+timerWith...方法对其进行调度,然后将其安排在自己的 runloop 上,[[NSRunLoop currentRunLoop] addTimer:timer forMode: NSRunLoopCommonModes]以便在所有 runloop 上运行它。让我知道这是否有效。

于 2012-06-18T21:03:04.980 回答
0

对于游戏,也许您应该使用 CADisplayLink 而不是 NSTimer。

于 2012-06-18T21:27:05.457 回答