iOS | 小心NSTimer中的内存泄漏

NSTimer大家都很熟悉,觉得用起来也很简单。然而,由NSTimer引起的内存泄漏,不经历过一次,一般很难察觉到。
下面看一段代码:

@interface ViewController()
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                              target:self
                                            selector:@selector(p_doSomeThing)
                                            userInfo:nil
                                             repeats:YES];

}

- (void)p_doSomeThing {
    // doSomeThing
}

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

- (void)dealloc {
     [self.timer invalidate];
}

@end

上面的代码主要是利用定时器重复执行p_doSomeThing方法,在合适的时候调用p_stopDoSomeThing方法使定时器失效。

能看出问题吗?在开始讨论上面代码问题之前,需要对NSTimer做一点说明。NSTimer的scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:方法的最后一个参数为YES时,NSTimer会一直保留目标对象,直到自身失效才释放目标对象。执行完任务后,一次性的定时器会自动失效;重复性的定时器,需要主动调用invalidate方法才会失效。

了解scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:最后一个参数含义之后,你发现何处出现问题了吗?

创建定时器时,当前控制器(创建定时器的那个控制器,为了描述方便,简称当前控制器)引用了定时器(引用定时器是因为后续要用到这个定时器对象),在给定时器添加任务时,定时器保留了self(当前控制器),这里就出现了第一个内存泄漏问题循环引用

循环引用

如果能在合适的时候打破循环引用,就不会有问题了。此时有两种选项:

1.控制器不再强引用定时器
2.定时器不再保留当前控制器

定时器即使不被引用,也可以正常运行。控制器可以弱引用定时器,这样就不存在循环引用了。第一种选择只解决了循环引用导致的内存泄漏问题,并不能解决当前控制器无法释放的问题,原因是Runloop对定时源的观察者要进行保留以便时间点到了进行调用,即定时器对象被Runloop强保留着,而定时器对象又强保留着当前控制器。

那么就只有同时使用第二种选择了。也就是合适的时候调用p_stopDoSomeThing方法。然而,合适的时机很难找到。假如这是一个验证码倒计时程序,你可以在倒计时结束时调用p_stopDoSomeThing方法。但是你不能确定用户一定会等倒计时结束才返回到上一级页面。或许你想在dealloc方法中使定时器失效,那就太天真了。此时定时器还保留着当前控制器,此方法是不可能调用的,因此会出现内存泄漏。或许在倒计时程序中,你可以重写返回方法,先调用p_stopDoSomeThing再返回,但这不是一个好主意。

该问题出现的根本原因就是无法确保一定会调用invalidate方法。针对这一问题,有些人会选择自己实现一个不保留目标对象的定时器。这里,并不打算采用那种从头写起的方法,正如AFN作者所说的

无数开发者尝试自己做一个简陋而脆弱的系统来实现网络缓存的功能,殊不知 NSURLCache 只要两行代码就能搞定且好上 100 倍。

这里采用block块的方法为NSTimer增加一个分类,具体细节看代码(程序员最好的语言是代码)。

//.h文件
#import <Foundation/Foundation.h>

@interface NSTimer (SGLUnRetain)
+ (NSTimer *)sgl_scheduledTimerWithTimeInterval:(NSTimeInterval)inerval
                                        repeats:(BOOL)repeats
                                          block:(void(^)(NSTimer *timer))block;
@end

//.m文件
#import "NSTimer+SGLUnRetain.h"

@implementation NSTimer (SGLUnRetain)

+ (NSTimer *)sgl_scheduledTimerWithTimeInterval:(NSTimeInterval)inerval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block{
    
    return [NSTimer scheduledTimerWithTimeInterval:inerval target:self selector:@selector(sgl_blcokInvoke:) userInfo:[block copy] repeats:repeats];
}

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

//控制器.m

#import "ViewController.h"
#import "NSTimer+SGLUnRetain.h"

//定义了一个__weak的self_weak_变量
#define weakifySelf  \
__weak __typeof(&*self)weakSelf = self;

//局域定义了一个__strong的self指针指向self_weak
#define strongifySelf \
__strong __typeof(&*weakSelf)self = weakSelf;

@interface ViewController ()

@property(nonatomic, strong) NSTimer *timer;

@end

@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    __block NSInteger i = 0;
    weakifySelf
    self.timer = [NSTimer sgl_scheduledTimerWithTimeInterval:0.1 repeats:YES block:^(NSTimer *timer) {
        strongifySelf
        [self p_doSomething];
        NSLog(@"----------------");
        if (i++ > 10) {
            [timer invalidate];
        }
    }];
}

- (void)p_doSomething {
    
}

- (void)dealloc {
      // 务必在当前线程调用invalidate方法,使得Runloop释放对timer的强引用(具体请参阅官方文档)
     [self.timer invalidate];
}
@end

上面的方法之所以能解决内存泄漏的问题,关键在于把保留转移到了定时器的类对象身上,这样就避免了实例对象被保留。

当我们谈到循环引用时,其实是指实例对象间的引用关系。类对象在App杀死时才会释放,在实际开发中几乎不用关注类对象的内存管理。下面的代码摘自苹果开源的NSObject.mm文件,从中可以看出,对于类对象,并不需要像实例对象那样进行内存管理。

+ (id)retain {
    return (id)self;
}

// Replaced by ObjectAlloc
- (id)retain {
    return ((id)self)->rootRetain();
}

+ (oneway void)release {
}

// Replaced by ObjectAlloc
- (oneway void)release {
    ((id)self)->rootRelease();
}

+ (id)autorelease {
    return (id)self;
}

// Replaced by ObjectAlloc
- (id)autorelease {
    return ((id)self)->rootAutorelease();
}

+ (NSUInteger)retainCount {
    return ULONG_MAX;
}

- (NSUInteger)retainCount {
    return ((id)self)->rootRetainCount();
}

iOS10中,定时器的API新增了block方法,实现原理与此类似,这里采用分类为NSTimer添加了带有block参数的方法,而系统是在原始类中直接添加方法,最终的行为是一致的。

需要内推每日优鲜的可以发邮件到shanggl@missfresh.cn
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容