NSTimer可靠的替代品 [英] NSTimer Reliable Alternatives
问题描述
我有一个应用程序应该每1秒记录一些事情,我现在正在使用 NSTimer
,但如果我的应用程序转换屏幕(或几乎其他任何东西,真的)它会使计时器变慢而导致读数不准确。
I have an application that is supposed to log certain things every 1 second and I'm currently using NSTimer
, but if my application transitions screens (or almost anything else, really) it slows down the timer a little bit making for inaccurate readings.
什么是可靠的替代品?我当前的代码如下:
What is a reliable alternative to use? My current code is as follows:
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(update) userInfo:nil repeats:YES];
推荐答案
NSTimer无法保证按时准时发射。但是你可以以比现在更可靠的方式使用NSTimer。当您使用 scheduledTimerWithTimeInterval
时,您将创建一个NSTimer,它在 NSDefaultRunLoopMode
的运行循环中进行调度。在使用UI时,此模式暂停,因此在有用户交互时,您的计时器不会触发。要避免此暂停,请使用模式 NSRunLoopCommonModes
。要做到这一点,你必须自己安排计时器:
NSTimer is not guaranteed to fire exactly on time, ever. But you can use an NSTimer in a much more reliable way than you are now. When you use scheduledTimerWithTimeInterval
you create an NSTimer which is scheduled in the run loop for NSDefaultRunLoopMode
. This mode is paused when the UI is being used, so your timers won't fire when there is user interaction. To avoid this pause use the mode NSRunLoopCommonModes
. To do this you will have to schedule the timer yourself like so:
timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(update) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
这篇关于NSTimer可靠的替代品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!