踩坑NSTimer

0.目录

概论,非主线程定时器导致的问题,定时器在界面滑动时候失效,定时器的准确性,定时器中的强引用。

1.概论

一般来讲在主线程创建一个定时器

self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(show) userInfo:nil repeats:YES];

scheduledTimerWithTimeInterval方法可以不用收动添加进runLoop
然后定时器就启动了。

//移除定时器
    [self.timer invalidate];

这个是唯一一个可以将计时器从RunLoop中移出的方法。

2.非主线程定时器导致的问题

如果线程没有开启RunLoop循环,定时器是不会起作用的,简单来讲NSTimer是在RunLoop中注册了一个TimerSource,RunLoop 会为其重复的时间点注册好事件。

    NSThread *newThread =  [[NSThread alloc] initWithTarget:self selector:@selector(startTimer) object:nil];
    [newThread start];

-(void)startTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(show) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}

这样定时器就可以在新的线程中运行了。
但是这样产生了一个问题 : 定时器虽然停止了,但是RunLoop并没有关闭,导致线程一直存在。

-(void)show{
    static int i = 0;
    NSLog(@"timer:%d",i);
    if (i == 3) {
        [self.timer invalidate];
        [self performSelector:@selector(test) withObject:nil afterDelay:1];
    }
    i++;
}
-(void)test{
    NSLog(@"RunLoop is alive");
}

/*
2018-04-18 16:40:07.733730+0800 [3781:2804455] timer:0
2018-04-18 16:40:08.733606+0800 [3781:2804455] timer:1
2018-04-18 16:40:09.733687+0800 [3781:2804455] timer:2
2018-04-18 16:40:10.732830+0800 [3781:2804455] timer:3
2018-04-18 16:40:11.734473+0800 [3781:2804455] RunLoop is alive

*/

这个问题的核心在于


[[NSRunLoop currentRunLoop] run];

If you want the run loop to terminate, you shouldn't use this method. Instead, 
use one of the other run methods and also che
ck other arbitrary conditions of 
your own, in a loop. A simple example would be:

手册上写的很清楚如果你想手动结束RunLoop就不应该调用run方法。
http://www.cocoabuilder.com/archive/cocoa/305204-runloop-not-being-stopped-by-cfrunloopstop.html给出了解决办法
CFRunLoopRun() 启动 runloop,通过 CFRunLoopStop() 结束runLoop

-(void)startTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(show) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    CFRunLoopRun();
}
-(void)show{
    static int i = 0;
    NSLog(@"timer:%d",i);
    if (i == 3) {
        CFRunLoopStop(CFRunLoopGetCurrent());
        [self performSelector:@selector(test) withObject:nil afterDelay:1];
    }
    i++;
}
-(void)test{
    NSLog(@"RunLoop is alive");
}

2018-04-18 16:51:52.480361+0800 [3789:2806195] timer:0
2018-04-18 16:51:53.480228+0800 [3789:2806195] timer:1
2018-04-18 16:51:54.476884+0800 [3789:2806195] timer:2
2018-04-18 16:51:55.479468+0800 [3789:2806195] timer:3

3.定时器在界面滑动时候失效

如果在TableView的界面创建一个定时器,那么在滑动的时候定时器是不会有效的。

2018-04-18 16:58:32.484047+0800 [3792:2806922] timer:0
2018-04-18 16:58:33.484158+0800 [3792:2806922] timer:1
2018-04-18 16:58:36.462380+0800 [3792:2806922] timer:2
2018-04-18 16:58:36.484182+0800 [3792:2806922] timer:3
2018-04-18 16:58:37.484158+0800 [3792:2806922] timer:4
``
注意时间在33到36秒时候我滑动了界面。
当然一个可行的解决办法是将定时器移到其他线程去执行,就像上一章讲的一样,不过还是应该知道为什么定时器会失效。

RunLoopMode
NSRunLoop对象是一系列RunLoopMode的集合,每个mode包括有这个模式下所有的Source源、Timer源和观察者。每次RunLoop调用的时候都只能调用其中的一个mode。

        NSDefaultRunLoopMode : App默认的mode,一般情况下App都是运行在这个mode下的。
        UITrackingRunLoopMode : 界面跟踪时的mode,一般用于ScrollView滚动的时候追踪的,保证滑动的时候不受其他事件影响。
        UIInitializationRunLoopMode : 在刚启动 App 时第进入的第一个 Mode,启动完成后就不再使用。
        GSEventReceiveRunLoopMode : 接受系统事件的内部 Mode,一般用不到。
        kCFRunLoopCommonModes : 占位mode,可以向其中添加其他mode用以检测多个mode的事件

注意每次RunLoop调用的时候都只能调用其中的一个mode这句话,在滑动的时候主线程的runLoop会切换到UITrackingRunLoopMode模式,而我们的定时器是默认添加到kCFRunLoopDefaultMode模式的,UITrackingRunLoopMode模式中的Timer显然没有包括创建的定时器。

切换到UITrackingRunLoopMode模式,定时器就可以正常使用了。

 [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:UITrackingRunLoopMode];

4.定时器的准确性

在上一章开始,我将定时器加入到RunLoop中的DefaultMode,导致滑动的时候定时器不起作用。

2018-04-18 16:58:32.484047+0800 [3792:2806922] timer:0
2018-04-18 16:58:33.484158+0800 [3792:2806922] timer:1
2018-04-18 16:58:36.462380+0800 [3792:2806922] timer:2
2018-04-18 16:58:36.484182+0800 [3792:2806922] timer:3
2018-04-18 16:58:37.484158+0800 [3792:2806922] timer:4

在我结束滑动的时候,在36.462380执行了一次.
我在Timer运行的时候手动让线程sleep两秒也得到了同样的结论。

-(void)sleepStart{
    [NSThread sleepForTimeInterval:2.0f];
}

事实上,定时器执行的确是不准确的,如果线程内部有耗时操作占有了该时间点本来应该触发的定时事件,定时事件会被推迟到线程空闲时候执行,如果等待时间过长,已经超过了下一次定时事件触发的时间点,则前一个事件会被跳过。
采用GCD实现定时器。

    static int count = 0;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_time_t start = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)); 
    uint64_t interval= 1.0 * NSEC_PER_SEC;
    dispatch_source_set_timer(self.timer, start, interval, 0); // NSEC_PER_SEC 
    dispatch_source_set_event_handler(self.timer, ^{
        count++;
        if (count == 4) {
            // 取消定时器
            dispatch_cancel(self.timer);
            self.timer = nil;
        }
    });
    dispatch_resume(self.timer);

这种方式类似于在非主线程中创建定时器,但是不需要在去和RunLoop打交道了。

5.定时器中的强引用。

-(void)startTimer{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(TimerHandle) userInfo:nil repeats:YES];
    self.timer = timer;
}

NSTimer轻易的就形成了引用环,不管是@selector还是block方式我们都应该避免,所以在停止定时器的同时,定时器属性需要置空。

-(void)stopTimer{
    [self.timer invalidate];
    self.timer = nil;
}

当然更好的办法可以采用YYTextWeakProxy中的办法。

@interface YYTextWeakProxy : NSProxy

/**
 The proxy target.
 */
@property (nullable, nonatomic, weak, readonly) id target;·
@end

@implementation YYTextWeakProxy
- (instancetype)initWithTarget:(id)target {
    _target = target;
    return self;
}
- (id)forwardingTargetForSelector:(SEL)selector {
    return _target;
}

用weak属性指向原有的target对象,并且采用消息转发机制重写forwardingTargetForSelector将正确的target返回。

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

推荐阅读更多精彩内容

  • 最近看了很多RunLoop的文章,看完很懵逼,决心整理一下,文章中大部分内容都是引用大神们的,但好歹对自己有个交代...
    小凉介阅读 6,565评论 12 79
  • 转自http://blog.ibireme.com/2015/05/18/runloop 深入理解RunLoop ...
    飘金阅读 938评论 0 4
  • 转载:http://www.cocoachina.com/ios/20150601/11970.html RunL...
    Gatling阅读 1,418评论 0 13
  • 一.人生格局的缘起是认知格局,人的人识格局主要体现在四个方面:一是关于时间认知,就是在思考问题时,如终站到时代的高...
    杨世京阅读 182评论 0 0
  • 第一天,周二3月1日18:25抵达巴塞罗那机场 到达机场先去酒店CHECK-IN,可选择的交通有: - 公交车AU...
    krisliz阅读 1,721评论 0 1