0

我一直在使用 Xcode 来实现计时器并运行计算。然而,计时器每隔一段时间就会跳过一个交互,这会抛出所有的计算。

- (void)Time
{

  if (running==false) return;

  NSTimeInterval currentTime = [NSDate timeIntervalSinceReferenceDate];
  NSTimeInterval elapsed = currentTime - startTime;

  int mins = (int) (elapsed / 60.0);

  elapsed -= mins* 60;
  int seconds = (int) (elapsed);
  elapsed -= seconds;
  int fraction = elapsed * 100.0;
  beepTime = [self Dec:seconds+elapsed];



  [self mod];



  label.text= [NSString stringWithFormat:@"%u:%02u.%.01u",mins,seconds,fraction/10];



  [self performSelector:@selector(Time) withObject:nil afterDelay:0.01];


}

这是一些日志的小样本

2012-08-14 20:25:04.659  RT 8.470000  BP 50.710000 MT 8.360000
2012-08-14 20:25:04.671  RT 8.470000  BP 50.720000 MT 8.370000
2012-08-14 20:25:04.682  RT 8.470000  BP 50.740000 MT 8.390000

请注意,已跳过 BP 50.730000 和 MT 8.380000。

有什么建议么?

干杯!

4

1 回答 1

1

如果您阅读有关 -performSelector:withObject:afterDelay: 的文档,则不能保证消息在 0.01 秒延迟后准确发送。相反,它说消息在 0.01 秒后被放入事件队列,并在轮到它时触发。

使用 NSTimer 的方法 + scheduleTimerWithTimeInterval:target:selector:userInfo:repeats: 可能会更好。

尽管计时器在当前运行循环中也与 performSelector 类似,但至少它不会在 0.01 + 中执行(执行 -Time 方法体所花费的时间)。

请注意,您只需调用该 NSTimer 方法一次,并使用其返回值使计时器无效。

于 2012-08-14T10:58:47.393 回答