NSTimer,NSRunLoop,autoreleasepool,多线程的爱恨情仇

引言

NSTimer内存泄漏真的是因为vc与timer循环引用吗?不是!

小伙伴们都知道,循环引用会造成内存泄漏,所谓循环引用无非就是强指针连成一个圈。但是,没连成圈的强指针引用同样可能造成内存泄漏,如NSTimer
注意:timer内存泄漏,部分童鞋认为是vc与timer循环引用造成的,这种说法是错误的!

正文

  • 内存泄漏

NSTimer内存泄漏的坑很多人都遇到过,为避免内存泄漏,部分童鞋是这么做的:

- (void)dealloc {
    [_timer invalidate];
}

更有甚者是这么做的:

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

然而并没有什么...用!

通常会这么写:

@interface NSTimerExample ()
@property (nonatomic, weak) NSTimer *timer0;
@property (nonatomic, weak) NSTimer *timer1;
@end

- (void)viewDidLoad {
    [super viewDidLoad];

    {
        NSTimer *one = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(tick:) userInfo:@"timer0" repeats:YES];
        _timer0 = one;
    }
}

+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo

这句代码timer会强引用target,即timer强引用vc,然而vc并没有强引用timer,哪来的vc与timer循环引用?但是,如果vc没有强引用timer,timer是如何存活的?
其实,上句代码默认将timer加入到currentRunLoop中,currentRunLoop会强引用timer,而currentRunLoop就是mainRunLoop,mainRunLoop一直存活,所以timer可以存活

如,我们还会显式的这么写(这种runloop模式,在scrollview滑动时同样可以工作):

- (void)viewDidLoad {
    [super viewDidLoad];

    {
        NSTimer *one = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(tick:) userInfo:@"timer1" repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:one forMode:NSRunLoopCommonModes];
        _timer1 = one;  
    }
}

回到问题,为啥vc的dealloc方法进不去?

关系图.png

从以上关系图可见,只要runLoop存活,vc必然存活,所以vc的dealloc方法自然就不会执行。因此,将timer的销毁方法放在dealloc中必然造成内存泄漏!

基于这种关系链,只要销毁两条线中的任意一条,就不会出现内存泄漏

所以出现了这种方案:

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSTimer *one = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(tick:) userInfo:@"timer0" repeats:YES];
    _timer0 = one;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [_timer0 invalidate];
}

这样做简单粗暴,直接将两条线都销毁,确实没有内存泄漏,可以满足部分场景。但是如果在这个vc基础上push一个新vc,而原vc的定时器还要继续工作,这种方案显然无法满足需求。
虽然NSRunLoop提供了addTimer接口,但是并没有提供removeTimer接口,显然,runLoop与timer这条线无法直接销毁,所以只能从vc与timer持有关系入手。
(CFRunLoopRef有这种接口)

CF_EXPORT void CFRunLoopAddTimer(CFRunLoopRef rl, CFRunLoopTimerRef timer, CFRunLoopMode mode);
CF_EXPORT void CFRunLoopRemoveTimer(CFRunLoopRef rl, CFRunLoopTimerRef timer, CFRunLoopMode mode);

思路很简单,以NSProxy为基类,创建一个weak proxy类,弱引用target即可,关系图如下:


新关系图.png

proxy弱引用vc,所以vc可以释放,当vc执行dealloc,在dealloc内部销毁timer即可

proxy可以这么写:

NS_ASSUME_NONNULL_BEGIN

@interface JKWeakProxy : NSProxy

@property (nonatomic, weak, readonly) id target;

+ (instancetype)proxyWithTarget:(id)target;

@end

NS_ASSUME_NONNULL_END
@implementation JKWeakProxy

- (instancetype)initWithTarget:(id)target {
    _target = target;
    return self;
}

+ (instancetype)proxyWithTarget:(id)target {
    return [[self alloc] initWithTarget:target];
}

- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
    return [_target methodSignatureForSelector:sel];
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    if ([_target respondsToSelector:invocation.selector]) {
        [invocation invokeWithTarget:_target];
    }
}

- (NSUInteger)hash {
    return [_target hash];
}

- (Class)superclass {
    return [_target superclass];
}

- (Class)class {
    return [_target class];
}

- (BOOL)isKindOfClass:(Class)aClass {
    return [_target isKindOfClass:aClass];
}

- (BOOL)isMemberOfClass:(Class)aClass {
    return [_target isMemberOfClass:aClass];
}

- (BOOL)conformsToProtocol:(Protocol *)aProtocol {
    return [_target conformsToProtocol:aProtocol];
}

- (BOOL)isProxy {
    return YES;
}

- (NSString *)description {
    return [_target description];
}

- (NSString *)debugDescription {
    return [_target debugDescription];
}

@end

此时代码只要这样写就可以了:

- (void)viewDidLoad {
    [super viewDidLoad];

    {
        JKWeakProxy *proxy = [JKWeakProxy proxyWithTarget:self];
        NSTimer *one = [NSTimer scheduledTimerWithTimeInterval:1.f target:proxy selector:@selector(tick:) userInfo:@"proxyTimer0" repeats:YES];
        _proxyTimer0 = one;
    }
}

- (void)dealloc {
    [_proxyTimer0 invalidate];
}

到这里,timer内存泄漏的坑已经完美解决。

再简单说说timer与runloop的组合使用

  • NSTimer && NSRunLoop && autoreleasepool && 多线程

前面已经说过如何在scrollview滑动时,让timer继续工作

  NSTimer *one = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(tick:) userInfo:@"timer1" repeats:YES];
  [[NSRunLoop currentRunLoop] addTimer:one forMode:NSRunLoopCommonModes];
  _timer1 = one; 

简单说下NSRunLoopCommonModes,NSRunLoopCommonModes是一种伪模式,它表示一组runLoopMode的集合,具体包含:NSDefaultRunLoopMode、NSTaskDeathCheckMode、UITrackingRunLoopMode。由于含有UITrackingRunLoopMode,所以可以在滑动时继续工作。

多线程中又是如何使用timer的呢?

    {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            JKWeakProxy *proxy = [JKWeakProxy proxyWithTarget:self];
            NSTimer *one = [NSTimer scheduledTimerWithTimeInterval:1.f target:proxy selector:@selector(tick:) userInfo:@"dispatchTimer0" repeats:YES];
            [[NSRunLoop currentRunLoop] run];
            _dispatchTimer0 = one;
        });
    }

多线程中需要显示启动runloop,为啥?

我们无法主动创建runloop,只能通过[NSRunLoop currentRunLoop]CFRunLoopGetCurrent()[NSRunLoop mainRunLoop]CFRunLoopGetMain()来获取runloop。除主线程外,子线程创建后并不存在runloop,主动获取后才有runloop。当子线程销毁,runloop也随之销毁。

上句代码为,获取子线程的runloop,并开启runloop,所以timer才可以正常运行。而在主线程中,mainRunLoop已经在程序运行时默认开启,所以不需要显示启动runloop。

问题又来了,runloop开启后,timer会一直在子线程中运行,所以子线程不会销毁,因此runloop无法自动停止,这似乎又是个死循环。既然无法自动停止,可以选择其他方式停止runloop

  1. runUntilDate
    {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            JKWeakProxy *proxy = [JKWeakProxy proxyWithTarget:self];
            NSTimer *one = [NSTimer scheduledTimerWithTimeInterval:1.f target:proxy selector:@selector(tick:) userInfo:@"dispatchTimer0" repeats:YES];
//            [[NSRunLoop currentRunLoop] run];
            
            NSDate *date = [NSDate dateWithTimeIntervalSinceNow:5.f];
            [[NSRunLoop currentRunLoop] runUntilDate:date];
            _dispatchTimer0 = one;
        });
    }

这样可以让runloop在5s后销毁,但是如果销毁时间不确定怎么办?

这涉及到runloop的运行机制:
runloop在指定mode模式下运行,每种mode至少要有一个mode item,如果runloop在某种mode模式下不含mode item,那么runloop直接退出。mode item有3种,分别为: Source/Timer/Observer,它们对应CFRunLoopSourceRef/CFRunLoopTimerRef/CFRunLoopObserverRef。Source为事件源,Timer为时间触发器,Observer为观察者。

OK,了解这些之后现在可以销毁子线程了

  1. invalidate

如果runloop在某种特停情况下要退出,由于上述代码runloop的mode item只有Timer,所以只要销毁timer,runloop就会退出

[_timer invalidate];
  • NSTimer并非真实的时间机制
    什么意思?即NSTimer并非基于我们现实生活中的物理时间。似乎还不是太好懂,可以从以下几点理解:
  1. timer需要在某种特定的runLoopMode下运行,如果当前mode为非指定mode,timer不会被触发,直到mode变成指定mode,timer开始运行
  2. 如果在指定mode下运行,但timer触发事件的时间点runloop刚好在处理其他事件,timer对应的事件不会被触发,直到下一次runloop循环
  3. 如果timer设置精度过高,由于runloop可能存在大量mode item,timer精度过高极有可能timer对应处理事件时间点出现误差(精度最好不超过0.1s)

Tip: runloop的内部是通过dispatch_source_t和mach_absolute_time()控制时间的,因此要实现精确的定时器,应使用dispatch_source_t或者mach_absolute_time()。CADisplayLink在某种程度上也可以当做定时器,但与NSTimer一样,并不准确。由于默认刷新频率与屏幕相同,因此可以用来检测FPS

  • autoreleasepool
    既然说到runloop,简单说下autoreleasepool。runloop会默认创建autoreleasepool,在runloop睡眠前或者退出前会执行pop操作

autoreleasepool的简单应用

    NSLog(@"begin");
    for (NSUInteger i = 0; i < 10000; i++) {
        NSString *str = [NSString stringWithFormat:@"hello %zd", i];
        NSLog(@"%@", str);
    }
    NSLog(@"end");

before.gif

可以看到,内存一直在增加,并且for循环结束后,内存仍然不会释放

可以将代码加上autoreleasepool:

   NSLog(@"begin");
    for (NSUInteger i = 0; i < 10000; i++) {
        @autoreleasepool {
            NSString *str = [NSString stringWithFormat:@"hello %zd", i];
            NSLog(@"%@", str);
        }
    }
    NSLog(@"end");
after.gif

可以看到,内存几乎没有变化

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

推荐阅读更多精彩内容

  • 一、什么是runloop 字面意思是“消息循环、运行循环”。它不是线程,但它和线程息息相关。一般来讲,一个线程一次...
    WeiHing阅读 8,128评论 11 111
  • 转自http://blog.ibireme.com/2015/05/18/runloop 深入理解RunLoop ...
    飘金阅读 983评论 0 4
  • Runloop实现了线程内部的事件循环。一个线程通常一次只能执行一个任务,任务执行完成线程就会退出,但是有时候,我...
    大猿媛阅读 229评论 0 1
  • RunLoop 是 iOS 和 OS X 开发中非常基础的一个概念,这篇文章将从 CFRunLoop 的源码入手,...
    iOS_Alex阅读 905评论 0 10
  • Runloop是iOS和OSX开发中非常基础的一个概念,从概念开始学习。 RunLoop的概念 -般说,一个线程一...
    小猫仔阅读 995评论 0 1