前言
在使用NSTimer,如果使用不得當特別會引起循環引用,造成內存泄露。所以怎么避免循環引用問題,下面我提出幾種解決NSTimer的幾種循環引用。
原因
當你在ViewController(簡稱VC)中使用timer屬性,由于VC強引用timer,timer的target又是VC造成循環引用。當你在VC的dealloc方法中銷毀timer,
發現VC被pop,VC的dealloc方法沒走,VC在等timer釋放才走dealloc,timer釋放在dealloc中,所以引起循環引用。
解決方案
- 在ViewController執行dealloc前釋放timer(不推薦)
- 對定時器NSTimer封裝
- 蘋果API接口解決方案(iOS 10.0以上可用)
- 使用block進行解決
- 使用NSProxy進行解決
一、在ViewController執行dealloc前釋放timer(不推薦)
- 可以在viewWillAppear中創建timer
- 可以在viewWillDisappear中銷毀timer
二、對定時器NSTimer封裝到PFTimer中
代碼如下:
//PFTimer.h文件
#import <Foundation/Foundation.h>
@interface PFTimer : NSObject
//開啟定時器
- (void)startTimer;
//暫停定時器
- (void)stopTimer;
@end
在PFTimer.m文件中代碼如下:
#import "PFTimer.h"
@implementation PFTimer {
NSTimer *_timer;
}
- (void)stopTimer{
if (_timer == nil) {
return;
}
[_timer invalidate];
_timer = nil;
}
- (void)startTimer{
_timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(work) userInfo:nil repeats:YES];
}
- (void)work{
NSLog(@"正在計時中。。。。。。");
}
- (void)dealloc{
NSLog(@"%s",__func__);
[_timer invalidate];
_timer = nil;
}
@end
在ViewController中使用代碼如下:
#import "ViewController1.h"
#import "PFTimer.h"
@interface ViewController1 ()
@property (nonatomic, strong) PFTimer *timer;
@end
@implementation ViewController1
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"VC1";
self.view.backgroundColor = [UIColor whiteColor];
//自定義timer
PFTimer *timer = [[PFTimer alloc] init];
self.timer = timer;
[timer startTimer];
}
- (void)dealloc {
[self.timer stopTimer];
NSLog(@"%s",__func__);
}
運行打印結果:
-[ViewController1 dealloc]
-[PFTimer dealloc]
這個方式主要就是讓PFTimer強引用NSTimer,NSTimer強引用PFTimer,避免讓NSTimer強引用ViewController,這樣就不會引起循環引用,然后在dealloc方法中執行NSTimer的銷毀,相對的PFTimer也會進行銷毀了。
三、蘋果系統API可以解決(iOS10以上)
在iOS 10.0以后,蘋果官方新增了關于NSTimer的三個API:
+ (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)interval repeats:
(BOOL)repeats block:(void (^)(NSTimer *timer))block
API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
- (instancetype)initWithFireDate:(NSDate *)date interval:
(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block
API_AVAILABLE(macosx(10.12), ios(10.0), watchos(3.0), tvos(10.0));
這三個方法都有一個Block的回調方法。關于block參數,官方文檔有說明:
the timer itself is passed as the parameter to this block when executed
to aid in avoiding cyclical references。
翻譯過來就是說,定時器在執行時,將自身作為參數傳遞給block,來幫助避免循環引用。使用很簡單,但是要注意兩點:
1.避免block的循環引用,使用__weak和__strong來避免
2.在持用NSTimer對象的類的方法中-(void)dealloc調用NSTimer 的- (void)invalidate方法;
四、使用block來解決
通過創建一個NSTimer的category名字為PFSafeTimer,在NSTimer+PFSafeTimer.h代碼如下:
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NSTimer (PFSafeTimer)
+ (NSTimer *)PF_ScheduledTimerWithTimeInterval:(NSTimeInterval)timeInterval block:
(void(^)(void))block repeats:(BOOL)repeats;
@end
NS_ASSUME_NONNULL_END
在NSTimer+PFSafeTimer.m中的代碼如下:
#import "NSTimer+PFSafeTimer.h"
@implementation NSTimer (PFSafeTimer)
+ (NSTimer *)PF_ScheduledTimerWithTimeInterval:(NSTimeInterval)timeInterval block:(void(^)(void))block repeats:(BOOL)repeats {
return [NSTimer scheduledTimerWithTimeInterval:timeInterval target:self selector:@selector(handle:) userInfo:[block copy] repeats:repeats];
}
+ (void)handle:(NSTimer *)timer {
void(^block)(void) = timer.userInfo;
if (block) {
block();
}
}
@end
該方案主要要點:
將計時器所應執行的任務封裝成"Block",在調用計時器函數時,把block作為userInfo參數傳進去。
userInfo參數用來存放"不透明值",只要計時器有效,就會一直保留它。
在傳入參數時要通過copy方法,將block拷貝到"堆區",否則等到稍后要執行它的時候,該blcok可能已經無效了。
計時器現在的target是NSTimer類對象,這是個單例,因此計時器是否會保留它,其實都無所謂。此處依然有保留環,然而因為類對象(class object)無需回收,所以不用擔心。
再調用如下:
#import "ViewController1.h"
#import "PFTimer.h"
#import "NSTimer+PFSafeTimer.h"
@interface ViewController1 ()
//使用category
@property (nonatomic, strong) NSTimer *timer1;
@end
@implementation ViewController1
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"VC1";
self.view.backgroundColor = [UIColor whiteColor];
__weak typeof(self) weakSelf = self;
self.timer1 = [NSTimer PF_ScheduledTimerWithTimeInterval:1.0 block:^{
__strong typeof(self) strongSelf = weakSelf;
[strongSelf timerHandle];
} repeats:YES];
}
//定時觸發的事件
- (void)timerHandle {
NSLog(@"正在計時中。。。。。。");
}
- (void)dealloc {
// [self.timer stopTimer];
NSLog(@"%s",__func__);
}
如果在block里面直接調用self,還是會保留環的。因為block對self強引用,self對timer強引用,timer又通過userInfo參數保留block(強引用block),這樣就構成一個環block->self->timer->userinfo->block,所以要打破這個環的話要在block里面弱引用self。
使用NSProxy來解決循環引用
原理如下圖:
代碼如下:
//PFProxy.h
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface PFProxy : NSProxy
//通過創建對象
- (instancetype)initWithObjc:(id)object;
//通過類方法創建創建
+ (instancetype)proxyWithObjc:(id)object;
@end
NS_ASSUME_NONNULL_END
在PFProxy.m文件中寫代碼
#import "PFProxy.h"
@interface PFProxy()
@property (nonatomic, weak) id object;
@end
@implementation PFProxy
- (instancetype)initWithObjc:(id)object {
self.object = object;
return self;
}
+ (instancetype)proxyWithObjc:(id)object {
return [[self alloc] initWithObjc:object];
}
- (void)forwardInvocation:(NSInvocation *)invocation {
if ([self.object respondsToSelector:invocation.selector]) {
[invocation invokeWithTarget:self.object];
}
}
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel {
return [self.object methodSignatureForSelector:sel];
}
@end
在使用的時候如下代碼:
#import "ViewController1.h"
#import "PFProxy.h"
@interface ViewController1 ()
//使用NSProxy
@property (nonatomic, strong) NSTimer *timer2;
@end
@implementation ViewController1
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = @"VC1";
self.view.backgroundColor = [UIColor whiteColor];
PFProxy *proxy = [[PFProxy alloc] initWithObjc:self];
self.timer2 = [NSTimer scheduledTimerWithTimeInterval:1.0 target:proxy selector:@selector(timerHandle) userInfo:nil repeats:YES];
}
//定時觸發的事件
- (void)timerHandle {
NSLog(@"正在計時中。。。。。。");
}
- (void)dealloc {
[self.timer2 invalidate];
self.timer2 = nil;
NSLog(@"%s",__func__);
}
@end
當pop當前viewController時候,打印結果:
-[ViewController1 dealloc]
通過PFProxy這個偽基類(相當于ViewController1的復制類),避免直接讓timer和viewController造成循環。