在使用NSTimer,若是使用不得當特別會引發循環引用,形成內存泄露。因此怎麼避免循環引用問題,下面我提出幾種解決NSTimer的幾種循環引用。ios
當你在ViewController(簡稱VC)中使用timer屬性,因爲VC強引用timer,timer的target又是VC形成循環引用。當你在VC的dealloc方法中銷燬timer,
發現VC被pop,VC的dealloc方法沒走,VC在等timer釋放才走dealloc,timer釋放在dealloc中,因此引發循環引用。macos
代碼以下:bash
//PFTimer.h文件
#import <Foundation/Foundation.h>
@interface PFTimer : NSObject
//開啓定時器
- (void)startTimer;
//暫停定時器
- (void)stopTimer;
@end
複製代碼
在PFTimer.m文件中代碼以下:app
#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__);
}
複製代碼
運行打印結果:ui
-[ViewController1 dealloc]
-[PFTimer dealloc]
複製代碼
這個方式主要就是讓PFTimer強引用NSTimer,NSTimer強引用PFTimer,避免讓NSTimer強引用ViewController,這樣就不會引發循環引用,而後在dealloc方法中執行NSTimer的銷燬,相對的PFTimer也會進行銷燬了。this
在iOS 10.0之後,蘋果官方新增了關於NSTimer的三個API:atom
+ (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參數,官方文檔有說明:spa
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方法;
經過建立一個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。
原理以下圖:
代碼以下:
//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形成循環。
原文地址:https://www.jianshu.com/p/fca3bdfca42f