iOS面试题iOS 开发

深入浅出了解NSTimer循环引用的原因

2018-09-12  本文已影响128人  Pusswzy

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无法立刻使用,需要添加到NSRunloop中才可以正常工作
    「After creating it, you must add the timer to a run loop manually by calling the addTimer:forMode: method of the corresponding NSRunLoop object。」
  • scheduledTimerWithTimeInterval创建出来的runloop已经被添加到当前线程的currentRunloop中来了。
    「Schedules it on the current run loop in the default mode。」

NSTimer与runloop的关系暂时不在本文详谈。我们先关注下timer为何会容易产生循环引用。 NSTimer会强引用target,等到自身'失效'时再释放此对象。
我们先假设开发中一个最常见的场景

#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。


retain cycle

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


几种不太好的解决方案

1.在dealloc中对timer进行释放

很多人都会在控制器的dealloc方法中写如下代码

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

认为在控制器销毁的时候顺便销毁timer,这样一来就万无一失了,殊不知因为循环引用dealloc方法根本没有执行。

2.在- (void)viewDidDisappear:(BOOL)animated中对timer进行释放

这种方式在平时开发中是比较是比较常见的且有效的,但是我认为有几点不好

- (void)viewDidDisappear:(BOOL)animated
{
    if (self.navigationController == nil) {
        [self.timer invalidate];
        self.timer = nil;
    }
}

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

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,本质都是一个地址。所以该方法无效。

4.不使用属性

你可能觉得不使用属性或成员变量可切断当前类对timer的强引用,但是当前类仍然会一直在内存中。原因如图 image.png

主线程的runloop在程序运行期间是不会销毁的, runloop引用着timer,timer就不会自动销毁。timer引用着target,target也不会销毁。


解决方案

1.使用中间代理方法

既然循环引用的原因是因为timer和控制器之间的强引用,那么是否可以使用一个中间代理得接触这个闭环呢?答案是可以的。整体构思如下图


Proxy

可以在timer与控制器之间使用一个proxy来解除两者之间的相互强引用。

首先声明一个.h文件
#import <Foundation/Foundation.h>
@interface LLTimerProxy1 : NSObject
+ (instancetype)proxyWithTarget:(id)target withSelector:(SEL)selector;
- (void)__execute;
@end
实现.m文件
#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 -> 弱引用着控制器
这样一来当控制器的引用计数为0的时候,会调用dealloc方法,在dealloc方法中对timer进行释放,timer释放的时候也会对proxy进行释放。这样一来就可以让timer的声明周期与控制器同步了

Log

补充

2.使用NSProxy

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

An abstract superclass defining an API for objects that act as stand-ins for other objects or for objects that don’t exist yet.

该类有两个方法,有runtime储备的同学应该会对这两个方法比较熟悉

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

NSProxy收到消息之后会在自己的方法列表中查找,如果没有则直接会进入消息转发。比NSObject类少了在父类的方法列表和动态解析的步骤,性能会更好。
因为Proxy可以实现消息转发,那么本身也不用持有选择子,这样代码会写的会更明确。

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

@interface LLTimerProxy : NSProxy
+ (instancetype)proxyWithTarget:(id)target;
@end
.m实现文件
#import "LLTimerProxy.h"

@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
使用方式
- (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__);
}

该方法比较简单,就不多赘述了。

上一篇 下一篇

猜你喜欢

热点阅读