【问题标题】:Error using xcode timer使用 xcode 计时器时出错
【发布时间】:2012-08-14 10:39:18
【问题描述】:

我一直在使用 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。

有什么建议吗?

干杯!

【问题讨论】:

    标签: xcode timer skip


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2020-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多