由于計時器會保留其目標對象,使用計時器時很容易引起循環(huán)引用,如下代碼所示:
@interface XXClass : NSObject
- (void)start;
- (void)stop;
@end
@implementation XXClass {
NSTimer *timer;
}
- (id)init {
return [super init];
}
- (void)dealloc {
[timer]
}
- (void)stop {
[timer invalidate];
timer = nil;
}
- (void)start {
timer = [NSTimerscheduledTimerWithTimeInterval:5.0
target:self
selector:selector(doSomething)
userInfo:nil
repeats:YES];
}
- (void)doSomething {
//doSomething
}
@end
大多數(shù)開發(fā)者可能都會這樣來實現(xiàn)定時器。創(chuàng)建定時器的時候,由于目標對象是self,所以要保留此實例。然而,因為定時器是用實例變量存放的,所以實例也保留了定時器,這就造成了循環(huán)引用。除非調(diào)用stop方法,或者系統(tǒng)回收實例,才能打破循環(huán)引用,如果無法確保stop一定被調(diào)用,就極易造成內(nèi)存泄露。
當指向XXClass實例的最后一個外部引用移走之后,該實例仍然會繼續(xù)存活,因為定時器還保留著它。而定時器對象也不可能被系統(tǒng)釋放,因為實例中還有一個強引用正在指向它。這種內(nèi)存泄露是很嚴重的,如果定時器每次輪訓都執(zhí)行一些下載工作,常常會更容易導致其他內(nèi)存泄露問題。
這個問題可以通過Block來解決:
@interface NSTimer (XXBlocksSupport)
+ (NSTimer *)xx_scheduledTimerWithTimeInterval:(NSTimeInterval)interval
block:(void(^)())block
repeats:(BOOL)repeats;
@end
@implementation NSTimer (XXBlocksSupport)
+ (NSTimer *)xx_scheduledTimerWithTimeInterval:(NSTimeInterval)interval
block:(void(^)())block
repeats:(BOOL)repeats
{
return [self scheduledTimerWithTimeInterval:interval
target:self
selector:@selector(xx_blockInvoke:)
userInfo:[block copy]
repeats:repeats];
}
+ (void)xx_blockInvoke:(NSTimer *)timer {
void (^block)() = timer.userinfo;
if(block) {
block();
}
}
@end
定時器現(xiàn)在的target是NSTimer類對象,這是個單例,此處依然有循環(huán)引用,然后類對象無需回收,所以不用擔心。
這套代碼并不能解決問題,例如:
- (void)start {
timer = [NSTimer xx_scheduledTimerWithTimeInterval:.5
block:^{
[self doSomething];
}
repeats:YES];
}
這段代碼里還是有循環(huán)引用,因為Block捕獲了self變量。此處只要改用weak引用,即可打破循環(huán)引用。
- (void)start {
__weak XXClass *weakSelf = self;
timer = [NSTimer xx_scheduledTimerWithTimeInterval:.5
block:^{
XXClass *strongSelf = weakSelf;
[strongSelf doSomething];
}
repeats:YES];
}
先定義了一個弱引用,令其指向self,然后使塊捕獲這個引用,而不直接去捕獲普通的self變量。也就是說,self不會為計時器所保留。當塊開始執(zhí)行時,立刻生成strong引用,以保證實例在執(zhí)行期間持續(xù)存活。
采用這種寫法之后,如果外界指向XXClass實例的最后一個引用將其釋放,則該實例就可為系統(tǒng)所回收了。