GCD倒计时的好处在于不用考虑是否定时器无法释放的问题,runloop的问题,还有精度更加高
使用GCD创建定时器方法

-(void)startCountDown:(NSInteger)maxTime{
    __block int time = 0;
    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);
    //如果有需要可以将定时器保存为全局变量
    _timer = timer;
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (time >= maxTime) {  //时间到了
            //清空计数
            time = 0;
            //时间到了关闭定时器
            dispatch_source_cancel(timer)
            dispatch_async(dispatch_get_main_queue(), ^{
                //在这里执行你要的操作
                do something...
            });
        }else{
            time++;
        }
    });
    dispatch_resume(timer);
}

相关文章:

  • 2021-05-23
  • 2022-12-23
  • 2021-11-30
  • 2021-11-25
  • 2022-12-23
  • 2022-12-23
  • 2021-08-21
  • 2021-12-02
猜你喜欢
  • 2021-08-18
  • 2022-12-23
  • 2022-12-23
  • 2018-03-02
  • 2021-10-16
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案