多个定时器同时使用的

做App肯定会碰到在一个VC中同时使用两个甚至多个定时器,这时候对定时器的选择就要慎重。

NSTimer的冲突

如果在一个类中同时使用两个NSTimer,调用不同selector,运行后就会出现冲突,定时器的重复时刻可能会错误调用另一个定时器所调用的selector,这就与NSTimer所加入的runloop有关系,需要把NSTimer创建不同的子Runloop中才能避免冲突。

dispatch_source_t的使用

避免以上的情况,最好选用GCD定时器,dispatch_source_t更加精确,并且使用Block运行要定时执行的内容。

dispatch_source_t的使用方法如下:

创建:

dispatch_source_t _timer;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.f * NSEC_PER_SEC, 0);
dispatch_source_set_event_handler(_timer, ^{
      //do something
});

在block中执行需要定时重复操作的内容。

猜你喜欢

转载自blog.csdn.net/u012380572/article/details/85198116