[iOS] NSTimer循环引用解决方法

1. NSTimer产生循环引用的原因

1.1 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中来了。

1.2 产生循环引用的例子
#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属性,并且timertarget是该控制器。当页面消失时,并不会调用dealloc方法timercontroller 产生了retain cycle,如下图所示:

image.png

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

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

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

  • dealloc方法中对timer进行释放? 也是不行的,上面的示例代码中,就是这么写的:
- (void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
}

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

  • 如果在控制器消失的时候释放timer不就行了吗?代码如下:
- (void)viewDidDisappear:(BOOL)animated
{
    if (self.navigationController == nil) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

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

  • 那我不使用属性,总该行了吗?
    image.png

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

2. 循环引用的解决方法

2.1 引入中间类

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

image.png

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

代码如下:

#import <Foundation/Foundation.h>
@interface Proxy : NSObject
+ (instancetype)proxyWithTarget:(id)target withSelector:(SEL)selector;
- (void)__execute;
@end

#import "Proxy.h"
@interface Proxy()
/** target */
@property (nonatomic, weak) id target;
/** SEL */
@property (nonatomic, assign) SEL selector;
@end

@implementation Proxy


+ (instancetype)proxyWithTarget:(id)target withSelector:(SEL)selector
{
    Proxy *proxy = [[Proxy 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
{
    Proxy *proxy = [Proxy 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
  • proxytarget 弱引用 controller

这样一来就打破了强引用的循环,当控制器的引用计数为0的时候,会调用dealloc方法,在dealloc方法中对timer进行释放,timer释放的时候也会对proxy进行释放,这样一来就可以让timer的生命周期与控制器同步了。

2.2 使用NSProxy子类

NSProxy是一个基类,是苹果创建出来专门做代理转发事件的基类,负责将消息转发到真正target的类。
该类有两个方法,这两个方法我们在消息转发流程中也看到了:

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

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

#import <Foundation/Foundation.h>

@interface Proxy : NSProxy
+ (instancetype)proxyWithTarget:(id)target;
@end

@interface Proxy ()
/** tatget */
@property (nonatomic, weak) id target;
@end

@implementation Proxy
+ (instancetype)proxyWithTarget:(id)target
{
    Proxy *proxy = [Proxy 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
{
    Proxy *proxy = [Proxy 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,这样就可以完成调用了。

2.3 使用block+weakSelf

NSTimeriOS10开放了两个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__);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容