iOS 使用CADisplayLink、NSTimer有什麼注意點?

強引用問題

平時咱們使用NSTimer或者CADisplayLink,若是不加處理直接使用系統提供的API方法,就有可能出現強引用問題(注意是強引用循環引用)。php

場景: 控制器A -> push -> 控制器B,控制器B的實現以下:objective-c

#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 並無銷燬。markdown

那麼這是爲何呢??? 是由於循環引用問題 ??,嗯,看着像,由於控制器B強引用timer,timer建立時會對target(即控制器B) 產生強引用,從而產生了強引用。網上不少文章也是這麼解釋的,其實也不能算錯,由於目前來看確實是有循環引用。 可是當你把控制器Btimer的引用改成弱引用 即:async

@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對它存在強引用。oop

那麼如何解決呢?其實只要將timer控制器B的引用改成弱引用便可,具體的方案其實網上均可以找到, 這裏也簡單說一下:ui

方案一: 換方法,使用block的方式實現。(簡單明瞭) 實現以下:atom

#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
複製代碼

方案二: 增長一個代理對象。以下: spa

實現代碼:代理

@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 底層課程

相關文章
相關標籤/搜索