GCD dispatch_source基本使用,创建GCD定时器与NSTimer的区别

可以使用GCD创建定时器

创建定时器:

    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    self.timer = timer;
    
    // 定时任务调度设置,4秒后启动,每个5秒运行
    dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW , 4);
    dispatch_source_set_timer(self.timer, time, 5 * NSEC_PER_SEC, 3 * NSEC_PER_SEC);
    
    dispatch_source_set_event_handler(self.timer, ^{
        // 定时任务
        NSLog(@"%s",__func__);
    });
    
    dispatch_source_set_cancel_handler(self.timer, ^{
        // 定时取消回调
        NSLog(@"source did cancel...");
    });
    
    // 启动定时器
    dispatch_resume(timer);

注意创建gcd定时器timer后,需要保存timer,需要有个引用引用timer,要不然timer会销毁

@property (nonatomic, strong) dispatch_source_t timer;

取消定时器

    dispatch_source_cancel(self.timer);
    self.timer = nil;

  

总结

GCD定时器

         1.时间调度很准确,时间是以纳秒为单位,NSTimer更加精确

         2.GCD是不受runloop的影响, 比如:拖动scrollView,不会影响GCD定时器的运行

NSTimer定时器

         1.时间调度可能会有误差,时间是以秒为单位,GCD timer精确

         2.runloop的影响比如:拖动scrollView,会影响定时器的运行

 

原文地址:https://www.cnblogs.com/HJiang/p/7497529.html