NSTimer循環引用的幾種解決方案


前言

在iOS中,NSTimer的使用是非常頻繁的,但是NSTimer在使用中需要注意,避免循環引用的問題。之前經常這樣寫:

- (void)setupTimer {
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}

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

由於self強引用了timer,同時timer也強引用了self,所以循環引用造成dealloc方法根本不會走,self和timer都不會被釋放,造成內存泄漏。

下面介紹一下幾種解決timer循環引用的方法。

1. 選擇合適的時機手動釋放timer(該方法並不太合理)

在之前自己就是這樣解決循環引用的:

  • 控制器中
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [self.timer invalidate];
    self.timer = nil;
}

 



  • view中
- (void)removeFromSuperview {
    [super removeFromSuperview];
    
    [self.timer invalidate];
    self.timer = nil;
}

 

 

在某些情況下,這種做法是可以解決問題的,但是有時卻會引起其他問題,比如控制器push到下一個控制器,viewDidDisappear后,timer被釋放,此時再回來,timer已經不復存在了。

所以,這種"方案"並不是合理的。

 

2. timer使用block方式添加Target-Action

這里我們需要自己在NSTimer的分類中添加類方法:

@implementation NSTimer (BlcokTimer)

+ (NSTimer *)bl_scheduledTimerWithTimeInterval:(NSTimeInterval)interval block:(void (^)(void))block repeats:(BOOL)repeats {
    
    return [self scheduledTimerWithTimeInterval:interval target:self selector:@selector(bl_blockSelector:) userInfo:[block copy] repeats:repeats];
}

+ (void)bl_blockSelector:(NSTimer *)timer {
    
    void(^block)(void) = timer.userInfo;
    if (block) {
        block();
    }
}
@end
 

通過block的方式,獲取action,實際的target設置為self,即NSTimer類。這樣我們在使用timer時,由於target的改變,就不再有循環引用了。 使用中還需要注意block可能引起的循環引用,所以使用weakSelf:

__weak typeof(self) weakSelf = self;
self.timer = [NSTimer bl_scheduledTimerWithTimeInterval:1 block:^{
     [weakSelf changeText];
} repeats:YES];
 

雖然沒有了循環引用,但是還是應該記得在dealloc時釋放timer。

3. 給self添加中間件proxy

考慮到循環引用的原因,改方案就是需要打破這些相互引用關系,因此添加一個中間件,弱引用self,同時timer引用了中間件,這樣通過弱引用來解決了相互引用,如圖:

 

接下來看看怎么實現這個中間件,直接上代碼:

@interface ZYWeakObject()

@property (weak, nonatomic) id weakObject;

@end

@implementation ZYWeakObject

- (instancetype)initWithWeakObject:(id)obj {
    _weakObject = obj;
    return self; } + (instancetype)proxyWithWeakObject:(id)obj { return [[ZYWeakObject alloc] initWithWeakObject:obj]; } 
@interface ZYWeakObject()

@property (weak, nonatomic) id weakObject;

@end

@implementation ZYWeakObject

- (instancetype)initWithWeakObject:(id)obj {
    _weakObject = obj;
    return self;
}

+ (instancetype)proxyWithWeakObject:(id)obj {
    return [[ZYWeakObject alloc] initWithWeakObject:obj];
}

 


僅僅添加了weak類型的屬性還不夠,為了保證中間件能夠響應外部self的事件,需要通過消息轉發機制,讓實際的響應target還是外部self,這一步至關重要,主要涉及到runtime的消息機制。
/**
 * 消息轉發,讓_weakObject響應事件
 */
- (id)forwardingTargetForSelector:(SEL)aSelector {
    return _weakObject;
}

- (void)forwardInvocation:(NSInvocation *)invocation {
    void *null = NULL;
    [invocation setReturnValue:&null];
}

- (BOOL)respondsToSelector:(SEL)aSelector {
    return [_weakObject respondsToSelector:aSelector];
}

 

 

接下來就可以這樣使用中間件了:

// target要設置成weakObj,實際響應事件的是self
ZYWeakObject *weakObj = [ZYWeakObject proxyWithWeakObject:self];
self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakObj selector:@selector(changeText) userInfo:nil repeats:YES];
 

結論

經測試,以上兩種方案都是可以解決timer的循環引用問題

代碼請移步github: Demo  https://github.com/zhouyangyng/timerRetainCycle

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM