Obj-c NSTimer - 比预期慢
Obj-c NSTimer - Slower than expected
我必须每 < 1 秒执行一次 繁重的 操作。我正在使用 NSTimer,但它不如我预期的那么准确...我正在使用 2 个计时器。一个更新我的模型中的数据,第二个更新我的视图(几个标签和自定义 'fancy-circle' 进度条)
好的...我的代码:
_valueTimer =
[NSTimer scheduledTimerWithTimeInterval:0.01
target:self
selector:@selector(counterTask)
userInfo:nil
repeats:YES];
_progressTimer =
[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(updateViews) // heavy stuff here
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_progressTimer
forMode:NSRunLoopCommonModes];
如您所见,_progressTimer
选择器每 0.1 秒 运行。
其中一个视图是我的 HH:MM:SS 时间(来自第一个计时器的数据!)。当我的进度条更新时,它显示的时间与实时时间不同(繁重的操作)-> 应用程序中的 10 秒 == 实时的 12 秒...差异太大了。当我评论我的进度条更新时 - 一切正常
你能告诉我如何在我的间歇后准确地强制我的计时器 运行 吗?或者在它无法处理时跳过一个周期?最重要的是不要慢下来...
谢谢
您可以尝试使用 CADisplayLink
计时器将 animation/drawing 与设备显示屏的刷新率同步(即,iOS 设备每秒 60 次)。
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLinkTimerFired:)];
//_displayLink.frameInterval = 3; // slows the updates for debugging
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
因为您的方法(这里是 handleDisplayLinkTimerFired
:) 会被频繁调用,所以您不想进行繁重的处理,否则会有丢帧的风险。
好的。我找到了解决方案。也许不完美,但它确实有效。
在 counterTask
方法中,我没有将我的 _actualTime
值增加 0.01... 我这样计算 'ticks' 之间的实际间隔:
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
startDate = currentDate;
_actualTime += timeInterval;
我必须每 < 1 秒执行一次 繁重的 操作。我正在使用 NSTimer,但它不如我预期的那么准确...我正在使用 2 个计时器。一个更新我的模型中的数据,第二个更新我的视图(几个标签和自定义 'fancy-circle' 进度条)
好的...我的代码:
_valueTimer =
[NSTimer scheduledTimerWithTimeInterval:0.01
target:self
selector:@selector(counterTask)
userInfo:nil
repeats:YES];
_progressTimer =
[NSTimer scheduledTimerWithTimeInterval:0.1
target:self
selector:@selector(updateViews) // heavy stuff here
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:_progressTimer
forMode:NSRunLoopCommonModes];
如您所见,_progressTimer
选择器每 0.1 秒 运行。
其中一个视图是我的 HH:MM:SS 时间(来自第一个计时器的数据!)。当我的进度条更新时,它显示的时间与实时时间不同(繁重的操作)-> 应用程序中的 10 秒 == 实时的 12 秒...差异太大了。当我评论我的进度条更新时 - 一切正常
你能告诉我如何在我的间歇后准确地强制我的计时器 运行 吗?或者在它无法处理时跳过一个周期?最重要的是不要慢下来...
谢谢
您可以尝试使用 CADisplayLink
计时器将 animation/drawing 与设备显示屏的刷新率同步(即,iOS 设备每秒 60 次)。
self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLinkTimerFired:)];
//_displayLink.frameInterval = 3; // slows the updates for debugging
[_displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
因为您的方法(这里是 handleDisplayLinkTimerFired
:) 会被频繁调用,所以您不想进行繁重的处理,否则会有丢帧的风险。
好的。我找到了解决方案。也许不完美,但它确实有效。
在 counterTask
方法中,我没有将我的 _actualTime
值增加 0.01... 我这样计算 'ticks' 之间的实际间隔:
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:startDate];
startDate = currentDate;
_actualTime += timeInterval;