定时器

问题:
1、NSTimer会retain你添加调用方法的对象吗?
2、NSTimer并不是每次都准确按你设定的时间间隔来触发的?
3、NSTimer需要和NSRunloop结合起来使用,是如何结合使用的?
4、除了用NSTimer实现定时器,还有什么方法?

1、定时器的初始化

-(void)regularTimer{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

-(void)regularTimerTwo{
    _timer = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

测试后得知方法1有效,方法2无效。
原因:方法1是创建了一个NSTimer并且以默认的mode加入到当前的runloop。方法2只是创建了一个NSTimer。
修改:方法2手动添加到runloop,代码如下:
[[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];

2、fire方法
NSTimer在加入到runloop中,timeInterval后自动触发。
使用fire()方法可以立刻触发,在重复执行的定时器中调用此方法后立即触发该定时器,但不会中断其之前的执行计划;

3、invalidate方法
这个是唯一一个可以将计时器从runloop中移出的方法。

在子线程开启NSTimer

[NSThread detachNewThreadSelector:@selector(threadTimer) toTarget:self withObject:nil];

-(void)threadTimer{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

发现使用上面的方法不起作用,说明在子线程上开启NSTimer与在主线程不同。这是因为在子线程中runloop是需要手动打开的。

-(void)threadTimer{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    //runloop在子线程上 是需要你手动打开的
    [[NSRunLoop currentRunLoop] run];
}

注意:在子线程开启的NSTimer要在子线程invalidate,如果在主线程invalidate,并没有将NSTimer从子线程的runloop中移出,会浪费runloop资源。

-(void)threadTimer{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    //子线程上调用invalidate
    [self performSelector:@selector(invalidateTimer) withObject:nil afterDelay:3.f];
    //runloop在子线程上 是需要你手动打开的
    [[NSRunLoop currentRunLoop] run];
    //如果在主线程上调用invalidate,下面的打印语句不会打印
    NSLog(@"==runloop exit==");
}

执行复杂操作对计时器的影响

[self regularTimer];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self busyCalculate];
    });

-(void)busyCalculate{
    NSUInteger count = 0xFFFFFFF;
    CGFloat num = 0.0;
    for(int i=0;i<count;i++){
        num = i/count;
    }
}

测试结果:定时器会卡住,然后过一段时间恢复。

NSTimer与runloop mode的关系

-(void)regularTimer{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

在开启NSTimer后,滚动tableview,发现定时器不工作。

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(@"runloop mode:%@",[NSRunLoop currentRunLoop].currentMode);
}

runloop它同一时刻只能在一个mode下运行,其他mode上的任务暂停
输出当前runloop的mode是:UITrackingRunLoopMode
由于定时器的初始化是在NSDefaultRunLoopMode这种模式下工作,所以当runloop的mode是UITrackingRunLoopMode时,定时器不工作。

如何让NSTimer在这种模式下也能工作能?

-(void)regularTimerTwo{
    _timer = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    //NSRunLoopCommonModes包含UITrackingRunLoopMode和NSDefaultRunLoopMode
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
}

循环引用

应用场景:进入一个viewController开启一个定时器,当我退出这个viewController的时候销毁定时器。

-(void)dealloc{
    [self invalidateTimer];
    NSLog(@"我被销毁了");
}

-(void)invalidateTimer{
    [_timer invalidate];
    _timer = nil;
}

测试发现使用上面的方式,当viewController退出的时候并没有调用dealloc,定时器也没有销毁,它照样在工作。
原因:创建NSTimer时
_timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
这个方法会对target的参数self有个强引用,直到timer调用invalidate方法。然而timer又是self的一个成员变量,也是强引用。
@property(nonatomic, strong)NSTimer *timer;
self->timer->self这样就变成了循环引用。timer的销毁依赖于dealloc方法中的invalidate,self的销毁依赖于timer的销毁。

解决方法
1、使用weak修饰self

-(void)planOne{
    __weak typeof(self)weakself = self;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:weakself selector:@selector(timerAction) userInfo:nil repeats:YES];
}

测试结果:无效果


image.png

原因:如上图self指向的那块内存,使用weakself是一个虚线指向那块内存,在NSTimer的初始化时,是对weakself指向的那块内存一个强引用,就是图上t所指的,其还是对self的一个强引用。

2、使用weak修饰timer

@property(nonatomic, weak)NSTimer *timer;

-(void)regularTimerTwo{
    _timer = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    //闪退
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
}

测试结果:运行初始化的时候闪退。
原因:timer是弱引用,在添加之前就已经释放了,为nil;

扩展:换种初始化方法

-(void)regularTimer{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

测试结果:使用上面这种方式初始化,不会闪退,运行正常。但是退出时也没有达到想要的效果(释放timer,释放self)
原因:使用这种方法初始化,runloop对timer有一个强引用。
runloop->timer->self self->timer timer无法调用invalidate释放

3、使用category为NSTimer添加方法

+(instancetype)timerWithTimerInterval:(NSTimeInterval)interval block:(void(^)(void))block repeate:(BOOL)repeat{
    return [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(timerAction:) userInfo:block repeats:repeat];
}

+(void)timerAction:(NSTimer *)timer{
    void(^block)(void) = timer.userInfo;
    if(block){
        block();
    }
}

调用初始化方法

-(void)planTwo{
    __weak typeof(self)weakSelf = self;
    _timer = [NSTimer timerWithTimerInterval:1.f block:^{
        [weakSelf timerAction];
    } repeate:YES];
    [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
}

测试结果:达到预期效果

在IOS10之后,系统提供了一个初始化方法,建议使用

__weak typeof(self)weakSelf = self;
    _timer = [NSTimer timerWithTimeInterval:1.f repeats:YES block:^(NSTimer * _Nonnull timer) {
        [weakSelf timerAction];
    }];

使用其他方式实现定时器功能

-(void)gcdTimer:(NSTimeInterval)interval repeat:(BOOL)repeat{
    dispatch_queue_t queue = dispatch_queue_create("timer", 0);
    timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, interval * NSEC_PER_SEC, 0 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        [self timerAction];
        if(!repeat){
            dispatch_cancel(timer);
        }
    });
    dispatch_resume(timer);
}

源码链接

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

推荐阅读更多精彩内容