runloop mode应用

亡羊补牢,为时不晚

面试被问到,一直没有注意过,在此补上。

问题描述

控制器中存在定时器以及tableview,当滑动tableview时,定时器停止计时,tableview再次停止后,计时恢复。

代码测试

使用label显示计时情况


计时
方案一:将定时器添加到其他线程,并开启runloop
dispatch_async(dispatch_get_global_queue(0, 0), ^{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(timeNumChange) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] run];
});

- (void)timeNumChange {

    self.count++;
    dispatch_async(dispatch_get_main_queue(), ^{
        self.timeNum.text = [NSString     stringWithFormat:@"runloop:%ld",self.count];
    
    });
}
方案二:将timer添加到指定mode(UITrackingRunLoopMode、NSRunLoopCommonModes)
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(timeNumChange) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:UITrackingRunLoopMode];

- (void)timeNumChange {

self.count++;
self.timeNum.text = [NSString stringWithFormat:@"runloop:%ld",self.count];

}

最后转载一篇更详细的文章:深入理解RunLoop

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

推荐阅读更多精彩内容

友情链接更多精彩内容