在GCD中,我们不能正常的使用NSTimer了,在子线程中runloop默认是关闭的,我们可以通过食用gcd的timer相关实现:
// 初始化一个gcd队列.
dispatch_queue_t timerQueue = dispatch_queue_create("test_timer_queue", 0);
// 创建 gcd timer.
dispatch_source_t _timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timerQueue);
double interval = 10 * NSEC_PER_SEC; // 间隔10秒
dispatch_source_set_timer(_timerSource, dispatch_time(DISPATCH_TIME_NOW, 0), interval, 0);
// 定时器block设置
dispatch_source_set_event_handler(_timerSource, ^{
// 定时处理代码
});
// 唤起定时器任务.
dispatch_resume(_timerSource);
当然如果非要在子线程中使用NSTimer,经过测试以下代码可以实现,将NSTimer 对象加入到主线程的runloop中:
NSTimer *timer = [NSTimer timerWithTimeInterval:10 target:self selector:@selector(timeOutAction) userInfo:nil repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
该方法创建一个timer的对象,不把它知道那个到run loop. (当创建之后,你必须手动的调用NSRunLoop下对应的方法 addTimer:forMode: 去将它制定到一个runloop模式中.)
在这里不能使用
- scheduledTimerWithTimeInterval: invocation: repeats:
该方法创建一个timer并把它指定到一个默认的runloop模式中,而子线程的runloop是默认关闭的,所以使用了,是没有效果的。