美文网首页
创建GCD定时器

创建GCD定时器

作者: 麻辣十三香小龙虾 | 来源:发表于2019-03-27 17:14 被阅读0次
/**
 创建一个定时器
 
 @param target 定时器持有者
 @param timeInterval 心跳时间
 @param handler stop=YES 销毁定时器
 */
void help_dispatch_timer(id target, double timeInterval, void (^handler)( BOOL * _Nonnull stop))
{
    __weak __typeof(target) weak_target  = target;
    __block BOOL stop = NO;
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0));
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, timeInterval * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        if (weak_target)  {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (handler) {
                    if (stop) {
                        long state = dispatch_source_testcancel(timer);
                        if (0==state) {
                            dispatch_source_cancel(timer);
                        }
                    }else{
                        handler(&stop);
                    }
                }else{
                    long state = dispatch_source_testcancel(timer);
                    if (0==state) {
                        dispatch_source_cancel(timer);
                    }
                }
            });
        } else {
            long state = dispatch_source_testcancel(timer);
            if (0==state) {
                dispatch_source_cancel(timer);
            }
        }
    });
    // 启动定时器
    dispatch_resume(timer);
}

举个栗子:

- (void)testDispatchTimer
{
    __weak typeof(self) self_weak_ = self;
    help_dispatch_timer(self, 2, ^(BOOL * _Nonnull stop) {
        self_weak_.label.text = [NSString stringWithFormat:@"%d",++count];
        if (6<=count) {
            *stop = YES;
        }
    });
}

相关文章

  • tableView或者scrollView滑动时 定时器 不响应

    先写解决办法 1. 2. 使用GCD创建定时器。GCD创建定时器不收Runloop的影响,并且GCD的定时器更精准...

  • GCD中的定时器(五)

    一. GCD中定时器的使用方法 创建一个队列 创建一个GCD的定时器 设置定时器的开始时间,间隔时间以及精准度 设...

  • GCD定时器

    创建GCD定时器 注意:默认创建的定时器对象需要强引用保住它的命,在任务执行中不被释放 定时器操作函数 dispa...

  • GCD定时器的实现

    GCD定时器 GCD定时器不受RunLoop约束,比NSTimer更加准时 证明,实现GCD定时器

  • GCD进入后台继续运行

    iOS GCD创建标准定时器,进入后台后任可继续定时

  • iOS - GCD中的定时器

    GCD定时器优点:① GCD定时器不受RunLoop约束② 比NSTimer更加准时。 GCD定时器用法敲 dis...

  • GCD定时器

    GCD定时器 GCD定时器不受RunLoop的影响,调用频率比较固定

  • GCD定时器使用

    iOS中的常用定时器分为这几类: NSTimer CADisplayLink GCD定时器 选择GCD定时器原因:...

  • GCD创建定时器

    GCD定时器使用小注意 栅栏函数 三等分 七等分 简单 直截了当的写法 巧用倍数约束 和 移动lastLabel ...

  • 创建GCD定时器

    举个栗子:

网友评论

      本文标题:创建GCD定时器

      本文链接:https://www.haomeiwen.com/subject/mqhtbqtx.html