定时器的使用总结

一、NSTimer
使用方式如下:

[NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(action) userInfo:nil repeats:NO];

优点:一行代码,简洁明了
坑坑坑坑坑:
1、只执行一次的timer在结束后计数器会减1,然后释放。重复执行的timer不会减1,如果不调用 [timer invalidate]会造成内存泄露,留下隐患;
2、执行时间不精确,会有误差。因为如果timer所在Runloop此时正在执行别的操作,那么就会出现延迟的情况,
3、当屏幕上存在tableview等类似的可滑动控件的时候,Timer有可能不会执行。因为在使用上述方式添加timer的时候,其RunloopMope是NSDefaultRunLoopMode,而当tableview滑动的时候,此时进入NSTrackingRunLoopMode,此时timer就不会执行,解决方法就是采用如下方式添加timer,并设置模式为NSRunLoopCommonModes,但是带来的负面影响就是timer的耗时操作可能会造成界面卡顿。

NSTimer *timer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

二、CADisplayLink

self.displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(handleDisplayLink:)];
[self.displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

个人理解:处理经度比Timer高点外,其他优缺点都差不多,只不过能按照屏幕的刷新频率来执行。

三、GCD

dispatch_queue_t timerQueue = dispatch_queue_create("timerQueue", 0);
timerSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, timerQueue);
double interval = 1 * NSEC_PER_SEC;
dispatch_source_set_timer(timerSource, dispatch_time(DISPATCH_TIME_NOW, 0), interval, 0);
// 设置定时任务
dispatch_source_set_event_handler(timerSource, ^{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self action];
    });
});
// 唤起定时器
dispatch_resume(timerSource);

优点:不用考虑内存泄露,线程问题
缺点:步骤繁琐

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1.属性readwrite,readonly,assign,retain,copy,nonatomic 各是什么作...
    曾令伟阅读 1,080评论 0 10
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,229评论 4 61
  • 2016.05.20 10:24 尘封已久的学习基础总结,最近公司项目不是很忙,终于抽空整理出来,现分享出来。 1...
    si1ence阅读 19,770评论 61 589
  • 加措活佛智慧之言 黑有什么可怕 天黑好赶路 逆境使人成熟 绝境使人醒悟 麦穗越成熟 就越懂得弯腰 而人越懂得弯腰 ...
    胡杨公主阅读 919评论 1 4
  • 我的灵感永远都是来自别人的文章。讨论自己一个个故事,都是让我心会停留在那些故事很久很久。 我喜欢过一个男孩子。这辈...
    路路66阅读 388评论 2 1