首页 > 技术文章 > iOS中的几种定时器详解

CoderLiLe 2016-07-22 17:40 原文

在软件开发过程中,我们常常需要在某个时间后执行某个方法,或者是按照某个周期一直执行某个方法。在这个时候,我们就需要用到定时器。

然而,在iOS中有很多方法完成以上的任务,经过查阅资料,大概有三种方法:NSTimer、CADisplayLink、GCD。接下来我就一一介绍它们的用法。

一、NSTimer

1.创建方法

/**
 *  类方法创建定时器对象
 *
 *  @property ti        之行之前等待的时间。比如设置为1.0,代表1秒后之行方法
 *  @property aTarget   需要执行方法的对象
 *  @property aSelector 需要执行的方法
 *  @property userInfo  保存定时器使用者的一些信息
 *  @property yesOrNo   是否需要循环
 *
 * @return 返回定时器对象
 */
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti
                                     target:(id)target
                                   selector:(SEL)aSelector
                                   userInfo:(id)userInfo
                                    repeats:(BOOL)repeats;

class func scheduledTimerWithTimeInterval(_ ti: NSTimeInterval,
                                   target aTarget: AnyObject,
                                 selector aSelector: Selector,
                                 userInfo userInfo: AnyObject?,
                                  repeats yesOrNo: Bool) -> NSTimer

2.释放方法

- (void)invalidate;

func invalidate()
  • 注意:
    调用创建方法后,target对象的计数器会加1,直到执行完毕,自动减1。如果是循环执行的话,就必须手动关闭,否则可以不执行释放方法。

3.特性

  • 存在延迟:
    不管是一次性的还是周期性的timer的实际触发事件的时间,都会与所加入的RunLoop和RunLoop Mode有关,如果此RunLoop正在执行一个连续性的运算,timer就会被延时出发。重复性的timer遇到这种情况,如果延迟超过了一个周期,则会在延时结束后立刻执行,并按照之前指定的周期继续执行。

  • 必须加入Runloop:
    使用上面的创建方式,会自动把timer加入MainRunloop的NSDefaultRunLoopMode中。如果使用以下方式创建定时器,就必须手动加入Runloop:

NSTimer *timer = [NSTimer timerWithTimeInterval:5 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
  • UIScrollView 拖动时执行的是 UITrackingRunLoopMode,会导致暂停定时器,等恢复为 NSDefaultRunLoopMode 时才恢复定时器。所以如果需要定时器在 UIScrollView 拖动时也不影响的话,建议添加到 UITrackingRunLoopMode 或 NSRunLoopCommonModes 中:

1.创建方法

/**
 *  类方法创建显示连接对象
 *
 *  @property target    执行方法的对象
 *  @property sel       需要执行的方法
 *
 * @return 返回显示连接对象
 */
+ (CADisplayLink *)displayLinkWithTarget:(id)target
                                selector:(SEL)sel;
 /**
 *  调度显示连接器去发送通知
 *
 *  @property runloop    运行循环
 *  @property mode       运行循环的模式
 *
 * @return 无
 */                              
- (void)addToRunLoop:(NSRunLoop *)runloop
             forMode:(NSString *)mode;
                                
init(target target: AnyObject,
     selector sel: Selector)
func addToRunLoop(_ runloop: NSRunLoop,
          forMode mode: String)

2.停止方法

/* 当把CADisplayLink对象add到runloop中后,selector就能被周期性调用,
类似于重复的NSTimer被启动了;执行invalidate操作时,CADisplayLink对
象就会从runloop中移除,selector调用也随即停止,类似于NSTimer的invalidate
方法。*/
- (void)invalidate;

func invalidate()

3.特性

  • 屏幕刷新时调用:
    CADisplayLink是一个能让我们以和屏幕刷新率同步的频率将特定的内容画到屏幕上的定时器类。CADisplayLink以特定模式注册到runloop后,每当屏幕显示内容刷新结束的时候,runloop就会向CADisplayLink指定的target发送一次指定的selector消息, CADisplayLink类对应的selector就会被调用一次。所以通常情况下,按照iOS设备屏幕的刷新率60次/秒

  • 延迟:
    iOS设备的屏幕刷新频率是固定的,CADisplayLink在正常情况下会在每次刷新结束都被调用,精确度相当高。但如果调用的方法比较耗时,超过了屏幕刷新周期,就会导致跳过若干次回调调用机会。如果CPU过于繁忙,无法保证屏幕60次/秒的刷新率,就会导致跳过若干次调用回调方法的机会,跳过次数取决CPU的忙碌程度。

  • 使用场景:
    从原理上可以看出,CADisplayLink适合做界面的不停重绘,比如视频播放的时候需要不停地获取下一帧用于界面渲染。

4.重要属性

  • frameInterval:
    NSInteger类型的值,用来设置间隔多少帧调用一次selector方法,默认值是1,即每帧都调用一次。

  • duration:
    readOnly的CFTimeInterval值,表示两次屏幕刷新之间的时间间隔。需要注意的是,该属性在target的selector被首次调用以后才会被赋值。selector的调用间隔时间计算方式是:调用间隔时间 = duration × frameInterval。

三、GCD方式

执行一次

double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); 
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ 
    //执行事件
});

重复执行

NSTimeInterval period = 1.0; // 设置时间间隔
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), period * NSEC_PER_SEC, 0); //每秒执行
dispatch_source_set_event_handler(_timer, ^{
     //在这里执行事件
});
dispatch_resume(_timer);

推荐阅读