Cocoa - NSTimer initWithFireDate:太晚了多秒?

时间:2013-12-10 15:14:29

标签: objective-c cocoa nsdate nstimer nsrunloop

我有一个简单的应用程序(目前)不会创建一个计时器:

     _time = [[NSTimer alloc] initWithFireDate: _nextDate
                                 interval: 0.0f
                                   target: self
                                 selector: @selector(trackTime)
                                 userInfo: nil
                                  repeats: NO];
[[NSRunLoop currentRunLoop] addTimer:_time forMode:NSRunLoopCommonModes];

在trackTime函数中,我检查了所述触发日期(_nextDate)与实际触发日期之间的差异:

     NSTimeInterval secondsBetween = [_nextDate timeIntervalSinceDate:[NSDate date]];

从结果来看,似乎该功能太迟被称为2到4秒。

这是正常的吗?我需要一个不同的runloop模式吗?我还能做些什么来获得更好的时机吗?

1 个答案:

答案 0 :(得分:0)

NSTimer不保证间隔,因为它取决于runloop机制。您可以查看有关runloop(https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html#//apple_ref/doc/uid/10000057i-CH16-SW1

的详细信息

也许你可以尝试从GCD发送dispatch_after。