美文网首页iOS面试题iOS-内存管理
浅谈NSTimer内存泄漏问题

浅谈NSTimer内存泄漏问题

作者: 低维质子 | 来源:发表于2016-11-12 21:06 被阅读855次

    今天在做项目的时候,遇到一个播放语音的需求,由于需要显示播放时长,于是用到了NSTimer那么问题来了,当控制器释放的时候,音频仍然在播放.利用XCode 8 新添加的内存泄漏查看工具Debug Memory Graph,我试着找到是否存在内存泄漏.

    图中所指为内存查看工具

    在没有播放时,JSQAudioMediaItem只被Controller引用,因此是没有问题的


    但是如果在播放的途中,将Controller给释放了,按道理来说AudioItem也应该被释放才对,观察dealloc方法,发现Audio并没有被释放,因为audioItem在播放音频之后,他的内存引用是这样的:

    audioItem还被AVAudioPlayer的delegate给引用了,当然,这不是事实的真相,尝试在音频播放的时候查看内存状态,于是真相浮出水面了:

    实际上AVAudioPlayer的delegate是assign的,所以不会有强引用问题,问题出在NSTimer
    身上.

    NSTimer和NSRunLoop

    我们都知道NSTimer要结合NSRunloop来使用,其实NSRunloop对NSTimer是强引用的
    所以在使用的时候建议对NSTimer弱引用,但这并不解决问题,问题在于NSTimer的target:
    类似于这样的语句:

    self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                                              target:self
                                                            selector:@selector(updateProgressTimer:)
                                                            userInfo:nil
                                                             repeats:YES];
    

    其实,NSTiemr会对它Target的对象有强引用,所以,self并不会被释放(因为定时器被MainRunloop引用,不会被释放,定时器再通过target强引用self,self也不会被释放)
    所以,能不能把self变成一个weakSelf呢?

    __weak typeof(self) weakSelf = self;
    self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:0.1
                                                              target:weakSelf
                                                            selector:@selector(updateProgressTimer:)
                                                            userInfo:nil
                                                             repeats:YES];
    

    但是这并没用.........释放NSTimer只有一个方法,那就是- invalidate
    于是去查阅苹果文档:

    Removes the object from all runloop modes (releasing the receiver if it has been implicitly retained) and releases the 'target' object.

    据官方介绍可知,- invalidate做了两件事,首先是把本身(定时器)从NSRunLoop中移除,然后就是释放对‘target’对象的强引用。可是,我们现在就是要在定时器的target释放的时候(dealloc)去调用- invalidate,而因为定时器强引用了target(也就是self),导致永远都不会调用self的dealloc方法,也就不会调用- invalidate了. 于是我们的定时器永远都会被Runloop持有,而我们的音频播放也不会在我们释放了控制器之后就停止播放了...(因为定时器强引用了self,也就是audioItem)

    那么解决方案是什么呢,一共有三个解决方案:

    • 利用NSNotificationCenter ,也就是注册一个通知,当控制器释放的时候,通知AudioItem,让它去调用 - invalidate方法
    • 如果你的定时器是被控制器本身引用的,那好了,你可以在- viewDidDisapper方法中调用- invalidate方法

    但是,如果你不想用通知(这东西一个项目里总是要用的,所以不想太泛滥)呢,而且你的定时器并不是被控制器引用,而是被某个继承于NSObject的类引用(就像我这种情况,AudioItem不是控制器),那么你就无法通过- viewDidDisapper来调用了,那么其实你可以重写一个NSTimer类,当然,这是假的Timer.

    思路就是,既然定时器的target会强引用self,那么为self创建一个接住这一波强引用的东东不就行了吗?
    于是:

    @interface CRSafeTimer ()
    
    @property (nonatomic, assign) SEL selector;
    
    @property (nonatomic, weak) NSTimer *timer;
    
    @property (nonatomic, weak) id target;
    
    @end
    @implementation CRSafeTimer
    
    - (void)run:(NSTimer *)timer {
        if (!self.target) {
            [self.timer invalidate];
        }else {
            [self.target performSelector:self.selector withObject:timer.userInfo];
        }
        
    }
    

    并且自己构造一个假的+ scheduledTimerWithTimeInterval 方法:

    + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval
                                         target:(id)target
                                       selector:(SEL)aSelector
                                       userInfo:(id)userInfo
                                       repeats :(BOOL)repeats {
        CRSafeTimer *crTimer = [[CRSafeTimer alloc] init];
        crTimer.target = target;
        crTimer.selector = aSelector;
        crTimer.timer = [NSTimer scheduledTimerWithTimeInterval:interval
                                                         target:crTimer
                                                       selector:@selector(run:)
                                                       userInfo:userInfo
                                                        repeats:repeats];
        return crTimer.timer;
    }
    

    这就ok了,我把CRSafeTimer上传了,欢迎大家使用.

    相关文章

      网友评论

        本文标题:浅谈NSTimer内存泄漏问题

        本文链接:https://www.haomeiwen.com/subject/fnvqpttx.html