我有一个应用程序,需要每隔1秒记录一些信息,目前我正在使用NSTimer
,但是如果我的应用程序切换屏幕或进行其他操作,会稍微减慢计时器速度,从而导致读数不准确。
有什么可靠的替代方案吗?我的当前代码如下:
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(update) userInfo:nil repeats:YES];
我有一个应用程序,需要每隔1秒记录一些信息,目前我正在使用NSTimer
,但是如果我的应用程序切换屏幕或进行其他操作,会稍微减慢计时器速度,从而导致读数不准确。
有什么可靠的替代方案吗?我的当前代码如下:
timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(update) userInfo:nil repeats:YES];
NSTimer不能保证精确按时触发。但您可以以比现在更可靠的方式使用NSTimer。当您使用 scheduledTimerWithTimeInterval
时,会创建一个被安排在NSDefaultRunLoopMode
下运行循环中的NSTimer。当UI正在使用时,该模式会暂停,因此当用户交互时,您的计时器不会触发。为避免此暂停,请使用NSRunLoopCommonModes
模式。为此,您需要自行预定计时器,如下所示:
timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(update) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
performSelectorInBackground
将计时器放在不同的线程中,但当它触发时它不会调用选择器(我猜是因为它在不同的线程中)。 - BaubNSTimer
不会创建自己的线程,它运行在创建它的线程上。 - jscsNSTimer
不是实时机制。 - jscs