iOS 使用CADisplayLink、NSTimer有什么注意点?

4,115 阅读4分钟

强引用问题

平时我们使用NSTimer或者CADisplayLink,如果不加处理直接使用系统提供的API方法,就有可能出现强引用问题(注意是强引用循环引用)。

场景: 控制器A -> push -> 控制器B,控制器B的实现如下:

#import "ViewControllerB.h"

@interface ViewController ()
@property (strong, nonatomic) NSTimer *timer;
@end

@implementation ViewControllerB

- (void)viewDidLoad {
    [super viewDidLoad];
    //每隔一秒钟调用一次timerTest
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES];
}

- (void)timerTest
{
    NSLog(@"%s", __func__);
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
    [self.timer invalidate];
}
@end

由控制器A进入控制器B, 定时器开始工作,但当点击返回, 由B页面返回A页面时,会发现控制器Bdealloc方法没有调用,说明控制器B 并没有销毁。

那么这是为什么呢??? 是因为循环引用问题 ??,嗯,看着像,因为控制器B强引用timer,timer创建时会对target(即控制器B) 产生强引用,从而产生了强引用。网上很多文章也是这么解释的,其实也不能算错,因为目前来看确实是有循环引用。 但是当你把控制器Btimer的引用改为弱引用 即:

@property (weak, nonatomic) NSTimer *timer;

你会惊奇的发现,前面的问题依旧存在。那么这又是为什么呢????,理应来说, 控制器B弱引用timer,那么当- (void)viewDidLoad 方法执行完,timer的作用域就结束了,应该挂掉才对, 事实上却没有,说明应该有别的对象强引用着timer。事实如此,这个别的对象其实就是Runloop对象。有源码为证(参考自GNUStep):

+ (NSTimer*) scheduledTimerWithTimeInterval: (NSTimeInterval)ti
				     target: (id)object
				   selector: (SEL)selector
				   userInfo: (id)info
				    repeats: (BOOL)f
{
  id t = [[self alloc] initWithFireDate: nil
			       interval: ti
				 target: object  // timer会强引用object
			       selector: selector
			       userInfo: info
				repeats: f];
  [[NSRunLoop currentRunLoop] addTimer: t forMode: NSDefaultRunLoopMode];
  RELEASE(t);
  return t;
}

可以看到,timer创建之后是直接加入到了当前的Runloop中,由此可得:控制器BtimerRunloop之间的引用关系:Runloop => timer => 控制器B。 所以 控制器B销毁不了的原因其实是timer对它存在强引用。

那么如何解决呢?其实只要将timer控制器B的引用改为弱引用即可,具体的方案其实网上都可以找到, 这里也简单说一下:

方案一: 换方法,使用block的方式实现。(简单明了) 实现如下:

#import "ViewController.h"
@interface ViewController ()
@property (strong, nonatomic) NSTimer *timer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 使用block方式,实现timer对vc的弱引用
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [weakSelf timerTest];
    }];
}
- (void)timerTest
{
    NSLog(@"%s", __func__);
}
- (void)dealloc
{
    NSLog(@"%s", __func__);
    [self.timer invalidate];
}
@end

方案二: 增加一个代理对象。如下:

实现代码:

@interface MJProxy : NSProxy
+ (instancetype)proxyWithTarget:(id)target;
@property (weak, nonatomic) id target;
@end

#import "MJProxy.h"

@implementation MJProxy

+ (instancetype)proxyWithTarget:(id)target
{
    // NSProxy对象不需要调用init,因为它本来就没有init方法
    MJProxy *proxy = [MJProxy alloc];
    proxy.target = target;
    return proxy;
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
    return [self.target methodSignatureForSelector:sel];
}

- (void)forwardInvocation:(NSInvocation *)invocation
{
    [invocation invokeWithTarget:self.target];
}
@end


#import "ViewController.h"
#import "MJProxy.h"

@interface ViewController ()
@property (strong, nonatomic) NSTimer *timer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:[MJProxy proxyWithTarget:self] selector:@selector(timerTest) userInfo:nil repeats:YES];
}

- (void)timerTest
{
    NSLog(@"%s", __func__);
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
    [self.timer invalidate];
}

@end

CADisplayLink 的使用也是一样的。

#import "ViewController.h"
#import "MJProxy.h"

@interface ViewController ()
@property (strong, nonatomic) CADisplayLink *link;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 保证调用频率和屏幕的刷帧频率一致,60FPS
    self.link = [CADisplayLink displayLinkWithTarget:[MJProxy proxyWithTarget:self] selector:@selector(linkTest)];
    [self.link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode]; 
}

- (void)timerTest
{
    NSLog(@"%s", __func__);
}
- (void)linkTest
{
    NSLog(@"%s", __func__);
}
- (void)dealloc
{
    NSLog(@"%s", __func__);
    [self.link invalidate];
}
@end

计时不准问题

NSTimer定时器是是误差的,原因与Runloop有关。 NSTimer依赖于RunloopNSTimer创建之后需要加入到Runloop中,然后Runloop每次循环都会检查一下NSTimer,看是否需要执行相应的任务。 但是Runloop的每一次循环所花费的时间是不固定的,任务较多,时间可能就长一点,任务少,时间可能就短一些。这是造成NSTimer有误差的原因。

一句话: NSTimer依赖于RunLoop,如果RunLoop的任务过于繁重,可能会导致NSTimer不准时

那iOS中如何才能准确的计时呢? 可以使用GCD定时器(与Runloop没啥关系,直接调用内核函数)。

#import "ViewController.h"

@interface ViewController ()
@property (nonatomic, strong) dispatch_source_t timer;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建串行队列
    dispatch_queue_t queue = dispatch_queue_create("com.long", DISPATCH_QUEUE_SERIAL);
    // 创建定时器
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    // 设置时间
    uint64_t start = 2;   // 2秒后开始
    uint64_t interval = 1;  // 间隔1秒
    dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, start * NSEC_PER_SEC), interval * NSEC_PER_SEC, 0);
    
    // 设置事件回调
    dispatch_source_set_event_handler(timer, ^{
        NSLog(@"11111111");  // 需要执行的任务
    });
//    也可以这样设定
//    dispatch_source_set_event_handler_f(timer, fireTimer);
    
    // 启动定时器
    dispatch_resume(timer);
    self.timer = timer; // 保住timer的命
}

void fireTimer() {
    NSLog(@"11111111");  // 需要执行的任务
}

@end

为了方便以后使用,下面将GCD的定时器进行一下封装。

.h文件

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface LCTimer : NSObject

+ (NSString *) execTask:(void(^)(void))task
                  start:(NSTimeInterval)start
               interval:(NSTimeInterval)interval
              repeating:(BOOL)repeating
                  async:(BOOL)async;


+ (NSString *) execTask:(id)target
                  selector:(SEL)selector
                  start:(NSTimeInterval)start
               interval:(NSTimeInterval)interval
              repeating:(BOOL)repeating
                  async:(BOOL)async;

+ (void)cancelTask:(NSString *)task;

@end

NS_ASSUME_NONNULL_END

.m文件

#import "LCTimer.h"

static NSMutableDictionary *timerMap_;
static dispatch_semaphore_t semaphore_;

@implementation LCTimer

// 类第一次接收到消息时调用
+ (void)initialize {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        timerMap_ = [[NSMutableDictionary alloc] init];
        semaphore_ = dispatch_semaphore_create(1);
    });
}

+ (NSString *)execTask:(void(^)(void))task start:(NSTimeInterval)start interval:(NSTimeInterval)interval repeating:(BOOL)repeating async:(BOOL)async {
    if (!task || start < 0 || (repeating && interval <= 0)) return nil;
    
    // 创建串行队列
    dispatch_queue_t queue = async ? dispatch_get_global_queue(0, 0) : dispatch_get_main_queue();
    
    // 创建定时器
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    // 设置时间
    dispatch_source_set_timer(timer, dispatch_time(DISPATCH_TIME_NOW, start * NSEC_PER_SEC), interval * NSEC_PER_SEC, 0);
    
    dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
    // 任务的Id
    NSString *taskId = [NSString stringWithFormat:@"%zd", timerMap_.count];
    [timerMap_ setObject:timer forKey:taskId];
    
    dispatch_semaphore_signal(semaphore_);
    
    // 设置事件回调
    dispatch_source_set_event_handler(timer, ^{
        task();
        if (!repeating) {
            [self cancelTask:taskId];
        }
    });
    
    // 启动定时器
    dispatch_resume(timer);
    
    return taskId;
}

+ (NSString *)execTask:(id)target selector:(SEL)selector start:(NSTimeInterval)start interval:(NSTimeInterval)interval repeating:(BOOL)repeating async:(BOOL)async {
    if (!target || !selector) return nil;
    
    return [self execTask:^{
        #pragma clang diagnostic push
        #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
        if ([target respondsToSelector:selector]) {
            [target performSelector:selector];
        }
        #pragma clang diagnostic push
    } start:start interval:interval repeating:repeating async:async];
}

+ (void)cancelTask:(NSString *)task {
    if (task.length <= 0) return;
    
    dispatch_semaphore_wait(semaphore_, DISPATCH_TIME_FOREVER);
    dispatch_source_t timer = [timerMap_ objectForKey:task];
    if (timer) {
        dispatch_source_cancel(timer);
        [timerMap_ removeObjectForKey:task];
    }
    dispatch_semaphore_signal(semaphore_);
}

@end

简单使用:

#import "ViewController.h"
#import "LCTimer.h"

@interface ViewController ()
@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, strong) NSString *taskId;
@property (nonatomic, strong) NSString *taskId2;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.taskId = [LCTimer execTask:^{
        NSLog(@"222222 %@", [NSThread currentThread]);
    } start:2 interval:1 repeating:YES async:NO];
    
    self.taskId2 = [LCTimer execTask:self selector:@selector(justForTest) start:2 interval:1 repeating:YES async:YES];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [LCTimer cancelTask:self.taskId];
    [LCTimer cancelTask:self.taskId2];
}

- (void)justForTest {
    NSLog(@"555555555");
}
@end

参考

MJ 底层课程