定时器的使用总结

2016-03-28  本文已影响59人  码蚁居然被用过了

一、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);

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

上一篇 下一篇

猜你喜欢

热点阅读