为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
iOS
引言

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

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,了解这些之后现在可以销毁子线程了

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
可以看到,内存几乎没有变化

点击查看更多内容
6人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
移动开发工程师
手记
粉丝
7
获赞与收藏
67

关注作者,订阅最新文章

阅读免费教程

感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消