NSTimer可靠的替代品

我有一个应用程序,应该每1秒记录一些事情,我现在正在使用NSTimer ,但如果我的应用程序转换屏幕(或几乎任何其他,真的),它会减慢计时器的一点点,使得读数不准确。

什么是可靠的替代品使用? 我目前的代码如下:

 timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(update) userInfo:nil repeats:YES]; 

NSTimer无法保证准时按时发射。 但是你可以以比现在更可靠的方式使用NSTimer。 使用scheduledTimerWithTimeInterval您将创建一个NSTimer,它在NSDefaultRunLoopMode的运行循环中进行NSDefaultRunLoopMode 。 在使用UI时,此模式暂停,因此在有用户交互时,您的计时器不会触发。 要避免此暂停,请使用模式NSRunLoopCommonModes 。 要做到这一点,你必须自己安排计时器,如下所示:

 timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(update) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; 

你可以:

  • 将NSTimer放在不同的线程中(它可能不会受到UI的影响)
  • 减少间隔(例如0.1秒),并在记录function中,检查是否是记录所需内容的“正确”时间。
Interesting Posts