GCD定时器不走set_event_handler和variable is not assignable missing block

今天尝试使用GCD创建定时器,发现一些小问题。转载请注明出处

初始错误代码

// 获取线程
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    // 创建一个定时器(dispatch_source_t本质还是个OC对象,创建出来的对象需要强引用)
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    // 设置定时器的各种属性(几时开始任务,每隔多长时间执行一次)
    // GCD的时间参数,一般是纳秒(1秒 = 10的9次方纳秒)
    // 何时开始执行第一个任务
    //    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3.0 * NSEC_PER_SEC)); //比当前时间晚3秒
    dispatch_time_t start = DISPATCH_TIME_NOW;// 当前时间执行
    
    // 时间间隔
    uint64_t interval = 1.0 * NSEC_PER_SEC;
    dispatch_source_set_timer(timer, start, interval, 0); // NSEC_PER_SEC 纳秒
    
    static int num = 0;
    // 设置回调
    dispatch_source_set_event_handler(timer, ^{
        
        NSLog(@"-----------%@", [NSThread currentThread]);
        
        NSLog(@"%d",num);
        num++;
    });
    
    // 启动定时器
    dispatch_resume(timer);

原因:dispatch_source_t timer是一个局部变量,只执行一次就会被release掉。换句话说必须创建成全局变量,否则执行一次就会被release掉。

后来修改:正确

dispatch_queue_t queen = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queen);
    dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC, 0 * NSEC_PER_SEC); // 每秒执行
    dispatch_source_set_event_handler(self.timer, ^{
        NSLog(@"444");
    });
    dispatch_resume(self.timer);

 

注意:

在 set_event_handler中 第一次写num 会报错,variable is not assignable missing block。

那么如何解决,就是在声明前加上 static

最后如何取消定时器,就是下面的代码:

dispatch_source_cancel(_timer)

posted @ 2018-07-12 14:16  weicy  阅读(383)  评论(0编辑  收藏  举报