今日写 Mac 平台 dylib 代码的时候, 发现一个问题. 当 NSTimer 在子线程中的时候, 是无法正常执行的.
错误代码如下:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timeScheduled:) userInfo:nil repeats:NO];
[NSRunLoop.currentRunLoop addTimer:timer forMode:NSDefaultRunLoopMode];
});
这是因为主线程中有一个 Runloop, 而子线程中一般没有 Runloop 直到你为其创建一个. 因此, 一般情况下,只有主线程才能够正确的执行 NSTimer, 而子线程则不会正确执行.
现将代码更正为:
dispatch_async(dispatch_get_main_queue(), ^{
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timeScheduled:) userInfo:nil repeats:NO];
[NSRunLoop.currentRunLoop addTimer:timer forMode:NSDefaultRunLoopMode];
});
这时候, Timer 就可以正确的跑起来了.