iOS定时器之dispatch_source_t

2,367 阅读3分钟

定时器简述

在iOS中,计时器是比较常用的,用于统计累加数据或者倒计时等,计时器大概有那么三种,分别是:

  NSTimer
  CADisplayLink
  dispatch_source_t

比较

1、NSTimer特性:

  • 存在延迟,不管是一次性的还是周期性的timer的实际触发事件的时间,都会与所加入的RunLoop和RunLoop Mode有关,如果此RunLoop正在执行一个连续性的运算,timer就会被延时出发。重复性的timer遇到这种情况,如果延迟超过了一个周期,则会在延时结束后立刻执行,并按照之前指定的周期继续执行。
  • 必须加入Runloop,使用scheduledTimerWithTimeInterval创建,会自动把timer加入MainRunloop的NSDefaultRunLoopMode中。如果使用以下方式创建定时器,就必须手动加入Runloop:
NSTimer *timer = [NSTimer timerWithTimeInterval:5 target:self 
selector:@selector(timerAction) userInfo:nil repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; 
  • 滑动时停止计时
1. kCFRunLoopDefaultMode:App的默认Mode,通常主线程是在这个Mode下运行
2. UITrackingRunLoopMode:界面跟踪 Mode,用于 ScrollView 追踪触摸滑动,保证界面滑动时不受其他 Mode 影响
3. UIInitializationRunLoopMode: 在刚启动 App 时第进入的第一个 Mode,启动完成后就不再使用,会切换
到kCFRunLoopDefaultMode
4. GSEventReceiveRunLoopMode: 接受系统事件的内部 Mode,通常用不到
5. kCFRunLoopCommonModes: 这是一个占位用的Mode,作为标记kCFRunLoopDefaultMode和
UITrackingRunLoopMode用,并不是一种真正的Mode 

如果选择的mode是default的话,当滑动scrollView的时候,定时器是会停止的,你可以将mode设置为common。

[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

2、CADisplayLink特性

特性:

  • 屏幕刷新时调用CADisplayLink是一个能让我们以和屏幕刷新率同步的频率将特定的内容画到屏幕上的定时器类。CADisplayLink以特定模式注册到runloop后,每当屏幕显示内容刷新结束的时候,runloop就会向CADisplayLink指定的target发送一次指定的selector消息, CADisplayLink类对应的selector就会被调用一次。所以通常情况下,按照iOS设备屏幕的刷新率60次/秒
  • 延迟iOS设备的屏幕刷新频率是固定的,CADisplayLink在正常情况下会在每次刷新结束都被调用,精确度相当高。但如果调用的方法比较耗时,超过了屏幕刷新周期,就会导致跳过若干次回调调用机会。如果CPU过于繁忙,无法保证屏幕60次/秒的刷新率,就会导致跳过若干次调用回调方法的机会,跳过次数取决CPU的忙碌程度。

使用场景:

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

3、dispatch_source_t特性

优点

  • 时间准确
  • 可以使用子线程,解决定时间跑在主线程上卡UI问题

对比

  • NSTimer会受到主线程的任务的影响,CADisplayLink会受到CPU负载的影响,产生延迟!!
  • dispatch_source_t可以使用子线程,而且使用leeway参数指定可以接受的误差来降低资源消耗!

使用实例

定时器按钮基于dispatch_source_t代码实现

CountDownButton.h 文件


#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface CountDownButton : UIButton

- (void)startCountDownTime:(int)time;

- (void)cancelTime;

@end

NS_ASSUME_NONNULL_END

CountDownButton.m 文件

#import "CountDownButton.h"

@interface CountDownButton ()
@property (nonatomic, strong) dispatch_source_t timer; //定时器
@property (nonatomic, copy) NSString *countDownTitle;  //按钮原生文本
@end

@implementation CountDownButton

- (void)dealloc {
    [self cancelTime]; 
}

- (void)startCountDownTime:(int)time withCountDownBlock:(void (^)(void))countDownBlock {
    [self initButtonData];
    [self startTime:time];
    if (countDownBlock) {
        countDownBlock();
    }
} 
- (void)cancelTime {
    if (_timer) { 
        dispatch_source_cancel(_timer);
        _timer = nil;
    }
}

- (void)initButtonData {
    if ([self.countDownTitle length] == 0) {
        self.countDownTitle = [NSString stringWithFormat:@"%@", self.titleLabel.text];
    }
}

- (void)startTime:(int)time {
    __block int timeout = time;
    [self cancelTime];
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0 * NSEC_PER_SEC, 0);
    WeakSelf(self);
    dispatch_source_set_event_handler(_timer, ^{
       StrongSelf(self);
      if (timeout <= 0) {
          [self cancelTime];
          dispatch_async(dispatch_get_main_queue(), ^{
              [self setTitle:self.countDownTitle forState:UIControlStateNormal];
               self.userInteractionEnabled = YES;  
          });
      } else {
          dispatch_async(dispatch_get_main_queue(), ^{
              StrongSelf(self);
            NSString *text = [NSString stringWithFormat:@"%02ds后重新发送", timeout];
            [self setTitle:text forState:UIControlStateNormal]; 
            self.userInteractionEnabled = NO;
          });
          timeout--;
      }
    });
    dispatch_resume(_timer);
} 
@end

参考

深入浅出 GCD 之 dispatch_source