关于NSTimer使用的内存泄漏问题之子线程

本文皆为个人总结,如有错误,欢迎指正,谢谢!

这里直奔主题吧,在另一篇文章《关于NSTimer使用的内存泄漏问题之主线程》中有对NSTimer比较详细的介绍。

Part 1 子线程中使用NSTimer遇到问题

  • 在子线程中使用NSTimer,主要问题就是子线程的释放问题。子线程如果没有释放,那么子线程的target便不能释放,所以问题的关键点就是子线程的释放。

Part 2 子线程的释放

  • 子线程的释放取决于runloop是否开启,那么问题定位的更精确了:runloop的开启与退出。
  • 子线程的runloop是需要我们手动开启的,苹果为我们提供了三种方式开启runloop。
// method 1 苹果的描述中有这样一句话:If you want the run loop to terminate, you shouldn't use this method. 
// 意思就是如果你想让这个runloop退出,那就不要用这个方法.
- (void)run;
// method 2 苹果的描述中有这样一句话: If no input sources or timers are attached to the run loop, this method exits immediately. 
// 意思就是当没有输入源或者timer加入到runloop中时,runloop会立即退出
- (void)runUntilDate:(NSDate *)limitDate;
// method 3 苹果描述中有这样一句话: If no input sources or timers are attached to the run loop, this method exits immediately and returns NO. 
// 意思就是当没有输入源或者timer加入到runloop中时,runloop会立即退出并返回NO.
- (BOOL)runMode:(NSRunLoopMode)mode beforeDate:(NSDate *)limitDate;

# 小结
// 1.如果我们通过run方法启动runloop是无法退出runloop的,所以子线程无法释放,其引用的target便不能释放.
// 2.在子线程中使用NSTimer,要通过runUntilDate: 或 runMode: beforeDateL:来启动runloop才可以控制子线程的释放.

#扩展
/*
 * 关于run的使用,我目前了解到的就是常驻线程(当然也有可能在其他方面用到,欢迎在评论中补充,谢谢)
 * 最典型的例子就是AFN2.xxx版本,里面就是创建了一个常驻线程.在AFN3.0只后的版本便不再创建常驻线程了.
 * 原因是从iOS9.0开始 苹果deprecated了 NSURLConnection。 替代方案就是NSURLSession。
   这里有篇文章可详细了解:https://www.jianshu.com/p/b5c27669e2c1
 */
// 创建常驻线程代码,这里AFN是用单例去创建的
+ (void)networkRequestThreadEntryPoint:(id)__unused object {
    @autoreleasepool {
        [[NSThread currentThread] setName:@"AFNetworking"];
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
        [runLoop run];
    }
}

+ (NSThread *)networkRequestThread {
    static NSThread *_networkRequestThread = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil];
        [_networkRequestThread start];
    });
    return _networkRequestThread;
}

Part 3 如何解决

  • 通过以上分析,解决方案便有了,这里我还是分两种情况
#pragma mark 情况1.不需要重复操作,repeats == NO(同主线程一样,系统会自动处理)
// 当timer执行完任务后,系统会自动从当前线程中移除timer,所以不需要手动处理

#pragma mark 情况2.需要重复操作,即repeats == YES
// 通过以下两种方式的其中一个开启runloop(参数应该不用介绍了吧……)
- (void)runUntilDate:(NSDate *)limitDate;
- (BOOL)runMode:(NSRunLoopMode)mode beforeDate:(NSDate *)limitDate;
# 切记不能够在dealloc中invalidate,原因是子线程与target在互相引用,必须先释放子线程

总结:

由于子线程与target的互相引用造成内存泄漏,所以要找到合适时机释放子线程,要想控制子线程的释放,就要通过正确的方式开启子线程的runloop。

参考代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"test";
    self.view.backgroundColor = [UIColor whiteColor];
    NSThread *threadA = [[NSThread alloc] initWithTarget:self selector:@selector(initTimer) object:nil];
    [threadA setName:@"testThreadA"];
    [threadA start];
    self.thread = threadA;

    //监听子线程的释放(为了证明下面@autoreleasepool{}的写法可以释放我们的子线程)
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(threadfinishTask:) name:NSThreadWillExitNotification object:nil];

}

- (void)threadfinishTask:(NSNotification *)notification{
    NSLog(@"==============================子线程被释放了!");
}

- (void)initTimer {

    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(refreshData) userInfo:@{@"key":@"value"} repeats:YES];
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];

}

- (void)refreshData {
    self.i ++;
    NSLog(@"%@",@(self.i));
}

- (void)cancelTimer {
    if (_timer) {
        if ([_timer isValid]) { // 如果timer还在runLoop中
            [_timer invalidate];
        }
        _timer = nil;
    }
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self performSelector:@selector(cancelTimer) onThread:self.thread withObject:nil waitUntilDone:YES];
}

- (void)dealloc {
    NSLog(@"dealloc~~~~~~~~~~~~ ");
}

参考文章:
《iOS 在子线程中NSTimer的启动和关闭》(思路是在文章底部一个叫“穷寇
”的评论内找到的)
《AFNetworking3.0后为什么不再需要常驻线程?》

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值