22.定时器的使用总结

1.子线程中开启定时器

具体代码如下:

@interface ZGKTimerVC ()

@property (nonatomic, strong) NSTimer *timer;

// 要关闭的runloop, 要保持同一线程
@property (nonatomic, assign) CFRunLoopRef runloop;
// 记录子线程
@property (nonatomic, strong) NSThread *backgroundThread;

@end

@implementation ZGKTimerVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
   // 子线程开启定时器
    [NSThread detachNewThreadSelector:@selector(startTimerOnBackgroundThread) toTarget:self withObject:nil];
    
    // 子线程上的定时器,必须要在子线程里面调用invalidate移除, 不要在主线程进行, 否则timer虽然停止了,但是runloop不会停止(每个子线程都有一个runloop, 需要找到对应线程关闭runloop)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (self.backgroundThread) {
            [self performSelector:@selector(cancelTimer) onThread:self.backgroundThread withObject:nil waitUntilDone:NO];
        }
    });
}

// 在子线程中执行定时器
- (void)startTimerOnBackgroundThread{
    NSLog(@"runloop start on backgroundThread");
    
    // 子线程上的定时器,必须要在子线程里面invalidate, 不要在主线程进行, 否则timer虽然停止了,但是runloop不会停止
    [self performSelector:@selector(cancelTimer) withObject:nil afterDelay:4.0];
    
    [self startTimer];
  
    // 停止了runloop才能执行
    NSLog(@"runloop end on backgroundThread");
}


- (void)startTimer{
    // 间隔之前先调用一次
    [self timerAction];
    
    // 方式一: 手动将timer放入runloop
    // timerWithTimeInterval:在主线程执行timer,需要将timer手动添加到runloop中, 才会执行
     self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    // runloop有两种模式, 分别是default和tracking
    // 所以定时器要加到两种模式中, NSRunLoopCommonModes
     [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    
    // 方法二: 系统已经将timer加入到了runloop
//    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    
// 子线程默认是关闭runloop的, 需要手动开启
//    [[NSRunLoop currentRunLoop] run];
    CFRunLoopRun();
}

- (void)timerAction{
    static int num = 0;
    
    NSLog(@"%d %@", num++, [NSThread currentThread]);
    
    // 满足条件后,停止当前的运行循环
    if (num == 10) {
        // 一旦停止了运行循环,CFRunLoopRun()的后续代码能够执行,执行完毕后,线程被自动销毁
        CFRunLoopStop(CFRunLoopGetCurrent());
    }
}


- (void)cancelTimer{
    NSLog(@"cancelTimer------");
    [self.timer invalidate];
    self.timer = nil;
}

- (void)dealloc{
    NSLog(@"timerVc dealloc");
    [self cancelTimer];
}

// 打印结果
2020-07-27 16:10:25.134929+0800 03-timer[2934:193644] runloop start on backgroundThread
2020-07-27 16:10:25.135111+0800 03-timer[2934:193644] 0 <NSThread: 0x600000053680>{number = 6, name = (null)}
2020-07-27 16:10:26.140051+0800 03-timer[2934:193644] 1 <NSThread: 0x600000053680>{number = 6, name = (null)}
2020-07-27 16:10:27.135630+0800 03-timer[2934:193644] 2 <NSThread: 0x600000053680>{number = 6, name = (null)}
2020-07-27 16:10:28.140374+0800 03-timer[2934:193644] 3 <NSThread: 0x600000053680>{number = 6, name = (null)}
2020-07-27 16:10:29.139387+0800 03-timer[2934:193644] cancelTimer------
2020-07-27 16:10:29.139609+0800 03-timer[2934:193644] runloop end on backgroundThread

注意点:

1.1 runloop在子线程是默认关闭的, 将定时器加入到runloop时,需要手动开启
1.2 停止定时器的方法有两种, 第一种是调用定时器的invalidate方法,将定时器移出runloop, runloop在没有输入源timer,就会自动停止, 线程销毁. 第二种,是调用CFRunLoopStop(CFRunLoopGetCurrent()), 直接停止runloop
1.3 显式开启runloop后, 会开启一个死循环, 要将runloop停止后,才能执行后续的代码,如: NSLog(@"runloop end on backgroundThread");
1.4 子线程上的定时器,必须要在子线程里面invalidate, 不要在主线程进行, 否则timer虽然停止了,但是runloop不会停止(每个子线程都有一个runloop, 需要找到对应线程关闭runloop), 如: 在主线程执行invalidate操作, timer随便停止了, 但是runloop的run方法后面的代码依旧没有执行
1.5 由于定时器是基于runloop的, 如果app存在大量运算时,定时器有时会不准确, 如果追求定时器的精确, 可以使用gcd的定时器.
1.6 创建timer时,self无论是正常的self还是weakSelf, 都会被timer强引用

2. 解决定时器的循环引用问题

2.1 使用带有block的timer构造法方法, 但是,这是iOS10推出的方法, 需要做兼容
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));

+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
2.2 通过timer的分类来实现解耦(模仿系统带block的timer)
@implementation NSTimer (NF)

+ (NSTimer *)nf_scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(block)block{
    
    return [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(selectorMethod:) userInfo:[block copy] repeats:repeats];
}

+ (void)selectorMethod: (NSTimer *)timer{
    
    block block = timer.userInfo;
    
    if (block) {
        block(timer);
    }
}
2.3 使用NSProxy的消息转发机制来解耦
NS_ASSUME_NONNULL_BEGIN

@interface ZGKProxy : NSProxy

@property (nonatomic, weak) id target;

// 为了防止绑定target,最好调用这个工厂方法创建对象
+ (instancetype)allocWithTarget: (id)target;

@end

NS_ASSUME_NONNULL_END

#import "ZGKProxy.h"

@implementation ZGKProxy

+ (instancetype)allocWithTarget: (id)target{
    ZGKProxy *proxy = [ZGKProxy alloc];
    proxy.target = target;
    return proxy;
}

#pragma mark - 这个函数抛出一个函数的签名,再由后面的forwardInvocation:去执行,为给定消息提供参数类型信息
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel{
    // sel => 调用的方法名, 即控制器的timerAction方法
    return [self.target methodSignatureForSelector:sel];
}

#pragma mark - NSInvocation封装了NSMethodSignature, 通过invokeWithTarget:方法将消息转发给其他对象,由被转发的对象执行该消息方法
- (void)forwardInvocation:(NSInvocation *)invocation{
    [invocation invokeWithTarget:self.target];
}

@end

#import "ZGKTimerVC.h"
#import "ZGKProxy.h"

@interface ZGKTimerVC ()

@property (nonatomic, strong) NSTimer *timer;

@end

@implementation ZGKTimerVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"NSProxy实现解耦";
    self.view.backgroundColor = UIColor.whiteColor;
    
    // 使用NSProxy消息转发机制,进行解耦
    ZGKProxy *proxy = [ZGKProxy allocWithTarget:self];
    // 如果没有设置target,则proxy进行函数签名的时候, 会直接crash
    /*
     Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSProxy doesNotRecognizeSelector:timerAction] called!'
     */
//    proxy.target = self;
    self.timer = [NSTimer timerWithTimeInterval:1.0 target:proxy selector:@selector(timerAction) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)timerAction{
    NSLog(@"执行定时器任务");
}

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


@end


这里需要特别注意的是:

2.3.1 proxy必须重写函数签名方法methodSignatureForSelector:和消息转发方法forwardInvocation:
2.3.2 绑定target对象, 如果没有绑定target会直接造成crash.
2.3.3 proxy的属性target, 必须是weak, 才能解耦

3. GCD的定时器

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270