使用NSTimer定义定时器需要将NSTimer对象添加到当前线程的RunLoop。否则在进行其他RunLoop切换时,会导致NSTimer受到影响,不能准确的进行调用。
而使用GCD创建定时器,更加精确,不需要使用RunLoop。
// 创建队列
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
// 创建定时器
dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,
0,
0,
queue);
// 需要使用强引用引用timer
self.timer = timer;
// 设置定时器开始时间,时间间隔,精确度
dispatch_source_set_timer(timer,
DISPATCH_TIME_NOW,
2.0 * NSEC_PER_SEC,
0 * NSEC_PER_SEC);
// 设置定时器回调
dispatch_source_set_event_handler(timer, ^{
NSLog(@"---%@--",[NSThread currentThread]);
});
// 开启定时器
dispatch_resume(timer);
0 Comments latest
No comments.