防止 NSTimer retain 作为 target 的 self

先吐槽一下这个标题,空格略蛋疼,不像中文,但是不写空格看上去则更诡异,求解决方案……

NSTimer会retain它的target,这样如果在控制器当中定义一个NSTimer,target指定为self,则会引起循环引用。

解决方案和防止block引用self一样,第一步需要把NSTimer的操作封装到一个block里,第二步则需要传递一个self的弱引用给block。

首先定义一个NSTimer的分类:

 1 #import <Foundation/Foundation.h>
 2 
 3 @interface NSTimer (BlockSupport)
 4 
 5 + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval block:(void(^)())block repeats:(BOOL)repeats;
 6 
 7 @end
 8 
 9 #import "NSTimer+BlockSupport.h"
10 
11 @implementation NSTimer (BlockSupport)
12 
13 + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval block:(void(^)())block repeats:(BOOL)repeats {
14     return [self scheduledTimerWithTimeInterval:interval target:self selector:@selector(blockInvoke:) userInfo:[block copy] repeats:repeats];
15 }
16 
17 + (void)blockInvoke:(NSTimer *)timer {
18     void (^block)() = timer.userInfo;
19     if (block) {
20         block();
21     }
22 }
23 
24 @end

这个分类支持使用Block创建NSTimer,把操作传递到了万能对象userInfo里面,之后在控制器当中以这样的方式创建:

1     __block typeof(self) weakSelf = self;
2     _timer = [NSTimer scheduledTimerWithTimeInterval:0.5 block:^{
3         [weakSelf doSth];
4     } repeats:YES];

如此一来,NSTimer就不会令控制器的引用计数+1了。

原文地址:https://www.cnblogs.com/Steak/p/3825577.html