NSTimer循环引用解决方法

作者: 沉江小鱼 | 来源:发表于2019-10-17 20:42 被阅读0次

    NSTimer产生循环引用的原因

    我们来看下系统给我们提供的NSTimer的初始化方法:

    + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
    + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
    
    + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(nullable id)userInfo repeats:(BOOL)yesOrNo;
    + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
    
    • timerWithTimeInterval 创建出来的timer无法立刻使用,需要添加到RunLoop中才可以正常工作。

    • scheduledTimerWithTimeInterval 创建出来的,已经被添加到当前线程的currentRunLoop中来了

    产生循环引用的例子:

    #import "ViewController.h"
    
    @interface ViewController ()
    @property (nonatomic, strong) NSTimer *timer;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad
    {
        self.timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(doSomething) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    }
    
    - (void)doSomething
    {
        NSLog(@"%s", __func__);
    }
    
    - (void)dealloc
    {
        [self.timer invalidate];
        self.timer = nil;
    }
    

    控制器中有一个timer属性,并且timer的target是该控制器,如下图所示,会形成一个retain cycle:


    image.png

    在不主动释放timer的前提下,那么控制器会一直强引用timer,timer内部的target也强引用着控制器,控制器的引用计数永远不会为0。这种内存泄漏问题尤其严重,因为timer还在不断的执行着任务。

    • 产生循环引用,我们肯定会首先想到使用weakSelf :
      如果把传入target的引用改为弱引用,这样一来引用线在timer指向当前类就断掉了,就不会形成循环引用了:
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer timerWithTimeInterval:1.0 target:weakSelf selector:@selector(doSomething) userInfo:nil repeats:YES];
    

    这种是错误的方法,传参跟使用block是两个不同的概念。weakSelfe最多使用的场景是在block内部中使用,block内部的机制会根据捕获的对象变量的指针类型(__weak, __strong)进行强引用或弱引用。
    但是参数传递的本质是将参数的地址传过去,无论是self或者是weakSelf,本质都是一个地址,所以该方法无效。

    • 可能会想到:在dealloc中对timer进行释放,看下面代码:
    - (void)dealloc
    {
        [self.timer invalidate];
        self.timer = nil;
    }
    

    首先,我们需要明白,当controller在销毁的时候才会执行dealloc,但是此时timer和controller是相互引用的,所以controller永远不会执行dealloc这个方法。

    • 又可能想到,那么在控制器消失的时候释放timer不就行了吗?
    - (void)viewDidDisappear:(BOOL)animated
    {
        if (self.navigationController == nil) {
            [self.timer invalidate];
            self.timer = nil;
        }
    }
    

    这种来说,其实并不太好,最好的办法是让timer跟当前类的生命周期绑定在一起,自动化的进行释放,减少非必要的代码书写。

    • 那我不使用属性,不就行了吗?


      image.png

      我们知道timer是加到Runloop中的,Runloop在运行期间是不会销毁的,Runloop引用者timer,timer就不会自动销毁,timer引用着target,target也不会销毁。

    重点还是怎么解决吧?

    1.使用中间代理方法

    既然循环引用的原因是因为timer和控制器之间的强引用,那么是否可以使用一个中间代理解除这个闭环呢?


    image.png

    像上图那样,我们可以使用一个proxy来解除两者之间的相互强引用。

    代码如下:

    #import <Foundation/Foundation.h>
    @interface LLTimerProxy1 : NSObject
    + (instancetype)proxyWithTarget:(id)target withSelector:(SEL)selector;
    - (void)__execute;
    @end
    
    #import "LLTimerProxy1.h"
    @interface LLTimerProxy1()
    /** target */
    @property (nonatomic, weak) id target;
    /** SEL */
    @property (nonatomic, assign) SEL selector;
    @end
    
    @implementation LLTimerProxy1
    
    
    + (instancetype)proxyWithTarget:(id)target withSelector:(SEL)selector
    {
        LLTimerProxy1 *proxy = [[LLTimerProxy1 alloc] init];
        proxy.target = target;
        proxy.selector = selector;
        return proxy;
    }
    
    - (void)__execute
    {
        if (_target && _selector) {
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
            [_target performSelector:_selector withObject:nil];
    #pragma clang diagnostic pop
        }
    }
    
    @end
    

    使用方式:

    - (void)viewDidLoad
    {
        LLTimerProxy1 *proxy = [LLTimerProxy1 proxyWithTarget:self withSelector:@selector(doSomething)];
        self.timer = [NSTimer timerWithTimeInterval:1.0 target:proxy selector:@selector(__execute) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    }
    
    - (void)doSomething
    {
        NSLog(@"%s", __func__);
    }
    
    - (void)dealloc
    {
        [self.timer invalidate];
        self.timer = nil;
        
        NSLog(@"%s", __func__);
    }
    

    从上面可以看到:
    NSTimer target 强引用 proxy
    proxy的target 弱引用 controller
    这样一来当控制器的引用计数为0的时候,会调用dealloc方法,在dealloc方法中对timer进行释放,timer释放的时候也会对proxy进行释放,这样一来就可以让timer的生命周期与控制器同步了。

    2.使用NSProxy

    NSProxy是一个基类,是苹果创建出来专门做代理转发事件的基类,负责将消息转发到真正target的类。
    该类有两个方法:

    • (void)forwardInvocation:(NSInvocation *)invocation;
    • (nullable NSMethodSignature *)methodSignatureForSelector:(SEL)sel

    NSProxy收到消息之后会在自己的方法列表中查找,如果没有则直接会进入消息转发,比NSObject类少了在父类的方法列表和动态解析的步骤,性能会更好。
    使用如下:

    #import <Foundation/Foundation.h>
    
    @interface LLTimerProxy : NSProxy
    + (instancetype)proxyWithTarget:(id)target;
    @end
    
    @interface LLTimerProxy ()
    /** tatget */
    @property (nonatomic, weak) id target;
    @end
    
    @implementation LLTimerProxy
    + (instancetype)proxyWithTarget:(id)target
    {
        LLTimerProxy *proxy = [LLTimerProxy alloc];
        proxy.target = target;
        return proxy;
    }
    
    - (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
    {
        if (!self.target || ![self.target respondsToSelector:sel]) {
            return [NSMethodSignature signatureWithObjCTypes:"v:@"];
        }
        return [self.target methodSignatureForSelector:sel];
    }
    
    - (void)forwardInvocation:(NSInvocation *)invocation
    {
        if (!self.target) {
            NSLog(@"target已经从内存中死掉了");
            return;
        }
        [invocation invokeWithTarget:self.target];
    }
    
    @end
    

    controller中使用:

    - (void)viewDidLoad
    {
        LLTimerProxy *proxy = [LLTimerProxy proxyWithTarget:self];
        self.timer = [NSTimer timerWithTimeInterval:1.0 target:proxy selector:@selector(doSomething) userInfo:nil repeats:YES];
        [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
    }
    
    - (void)doSomething
    {
        NSLog(@"%s", __func__);
    }
    
    - (void)dealloc
    {
        [self.timer invalidate];
        self.timer = nil;
        
        NSLog(@"%s", __func__);
    }
    

    可以发现Proxy类并没有引用着selector,因为proxy类并没有doSomething方法,所有直接进入了消息转发步骤.在消息转发中将消息接受者转发给自身持有的target,这样就可以完成调用了。

    3.使用block+weakSelf

    NSTimer在iOS10开放了两个API

    /// Creates and returns a new NSTimer object initialized with the specified block object. This timer needs to be scheduled on a run loop (via -[NSRunLoop addTimer:]) before it will fire.
    /// - parameter:  timeInterval  The number of seconds between firings of the timer. If seconds is less than or equal to 0.0, this method chooses the nonnegative value of 0.1 milliseconds instead
    /// - parameter:  repeats  If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.
    /// - parameter:  block  The execution body of the timer; the timer itself is passed as the parameter to this block when executed to aid in avoiding cyclical references
    + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
    
    /// Creates and returns a new NSTimer object initialized with the specified block object and schedules it on the current run loop in the default mode.
    /// - parameter:  ti    The number of seconds between firings of the timer. If seconds is less than or equal to 0.0, this method chooses the nonnegative value of 0.1 milliseconds instead
    /// - parameter:  repeats  If YES, the timer will repeatedly reschedule itself until invalidated. If NO, the timer will be invalidated after it fires.
    /// - parameter:  block  The execution body of the timer; the timer itself is passed as the parameter to this block when executed to aid in avoiding cyclical references
    + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
    

    使用方式:

    - (void)viewDidLoad
    {
        __weak typeof(self) weakSelf = self;
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
            [weakSelf doSomething];
        }];
    }
    
    - (void)doSomething
    {
        NSLog(@"%s", __func__);
    }
    

    我感觉需要了解一下NSTimer的实现比较好?

    相关文章

      网友评论

        本文标题:NSTimer循环引用解决方法

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