GCD timer中不写dispatch_source_cancel不跑

今天在用GCD中timer时,在

dispatch_source_set_event_handler(timer, ^{
        <#code to be executed when timer fires#>
    });

中不写

dispatch_source_cancel(timer);

发现handler的block根本不执行;

代码如下

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self testGCDTimer];
}


- (void)testGCDTimer {
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(0, 0));
    dispatch_source_set_timer(timer, dispatch_walltime(0, 0), 1.0 * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    NSLog(@"block开始");
    dispatch_source_set_event_handler(timer, ^{
        NSLog(@"这里是block");
        if (0) {
            //dispatch_source_cancel(timer);
        }
    });
    NSLog(@"block结束");
    dispatch_resume(timer);
}

当注释掉dispatch_source_cancel(timer);时,输出如下

2019-05-19 22:46:29.382412+0800 TimerTest[98542:7229224] block开始
2019-05-19 22:46:29.382608+0800 TimerTest[98542:7229224] block结束

不注释时,timer的block才运行(即使这个条件永远不能满足)输出如下

2019-05-19 22:47:13.377154+0800 TimerTest[98575:7229910] block开始
2019-05-19 22:47:13.377337+0800 TimerTest[98575:7229910] block结束
2019-05-19 22:47:13.377481+0800 TimerTest[98575:7229951] 这里是block
2019-05-19 22:47:14.377279+0800 TimerTest[98575:7229951] 这里是block
2019-05-19 22:47:15.378388+0800 TimerTest[98575:7229953] 这里是block
2019-05-19 22:47:16.378343+0800 TimerTest[98575:7229953] 这里是block
2019-05-19 22:47:17.377606+0800 TimerTest[98575:7229953] 这里是block
2019-05-19 22:47:18.378223+0800 TimerTest[98575:7229953] 这里是block
2019-05-19 22:47:19.377602+0800 TimerTest[98575:7229953] 这里是block
2019-05-19 22:47:20.378063+0800 TimerTest[98575:7229953] 这里是block
2019-05-19 22:47:21.377446+0800 TimerTest[98575:7229952] 这里是block
2019-05-19 22:47:22.378032+0800 TimerTest[98575:7229952] 这里是block
2019-05-19 22:47:23.377601+0800 TimerTest[98575:7229952] 这里是block

后记:

最近又试了一下,发现只要是在新建该timer的文档中,有写

dispatch_source_cancel(timer);

这句代码,就没问题,比如常这样写

- (void)dealloc {
      dispatch_source_cancel(_timer);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容