1.1 NSTimer 与运行循环的关系
Timer 初始化部分源码如下:
timer 初始化时,会对传入的target 和 info 执行 retain , 即使传入的是一个weak 修饰的对象,也会是强引用。
- (id) initWithFireDate: (NSDate*)fdinterval: (NSTimeInterval)titarget: (id)objectselector: (SEL)selectoruserInfo: (id)inforepeats: (BOOL)f{..._target = RETAIN(object);_selector = selector;_info = RETAIN(info);...}
运行循环加入timer 的部分源码:
运行循环强持有一个 timers 数组,在添加 timer 的时候,加到了timers 数组中,所以运行循环强持有timer。
- (void) addTimer: (NSTimer*)timerforMode: (NSString*)mode{GSRunLoopCtxt *context;GSIArray timers;unsigned i;...context = NSMapGet(_contextMap, mode);...timers = context->timers;...GSIArrayAddItem(timers, (GSIArrayItem)((id)timer));...}
总结:定时器需要依赖运行循环上才能执行, 且被运行循环强持有。
1.2 NSTimer 的使用
1. 自动加入运行循环的类方法
以下方法是自动加入到当前的运行循环且mode为kCFRunLoopDefaultMode
+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;+ (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;
2. 需要手动加入运行循环的类方法
+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;+ (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
使用方法:
/*** 打开网络请求访问超时定时器*/- (void)startTimer {if (!self.timeoutTimer) {self.timeoutTimer = [NSTimer timerWithTimeInterval:DEFAULT_TIMEOUT_INTERVAL target:self selector:@selector(checkTaskStatus) userInfo:nil repeats:NO];[self.runloop addTimer:self.timeoutTimer forMode:NSRunLoopCommonModes];}}/*** 关闭网络请求访问超时定时器*/- (void)stopTimer {if (self.timeoutTimer) {[self.timeoutTimer invalidate];self.timeoutTimer = nil;}}
3. 需要手动加入运行循环的对象方法
- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)rep;- (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;
1.3 NSTimer 的避坑指南
1.mode 切换导致timer 停止
- 如果发生页面滚动,主运行循环的模式就会自动切换到UITrackingRunLoopMode,而我们的 timer 只添加到了 kCFRunLoopDefaultMode 的 mode 上,tracking mode 下没有timer 事件源,所以 timer 会停止。
- 如果想让滚动和默认情况下 timer 都正常工作,需要将 timer 添加到 kCFRunLoopCommonModes上。 ```objectivec // 创建timer self.timer = [NSTimer scheduledTimerWithTimeInterval:_logReportCircle target:self selector:@selector(timerUpdate) userInfo:nil repeats:YES]; [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
// 销毁timer [self.timer invalidate]; self.timer = nil;
<a name="cH7hc"></a>### 2. Timer 与 VC 的循环引用问题在我们上面的写法儿中,- VC 持有 Timer, 对 Timer 是强引用- Timer 的 Target 设置的是 VC ,Timer 对 VC 也是强引用,直到 **Timer invalidate, Timer 内部才会释放对 Target 和 info 的强持有。**- 同时,Timer 被添加到了Runloop, 那么 Runloop 也会强引用 Timer。- repeats 为 NO 的在执行一次后,会自动从运行循环移除。- repeats 为 YES 的,直到 **Timer invalidate, 才会从运行循环中移除**三者间的关系如下图所示:<br /><br />这样就出现了**循环引用**,产生 VC dealloc 无法执行,无法释放的问题。<a name="ykw7H"></a>#### 解决方案1:返回时销毁Timer比较常用的做法是在点击返回按钮的时候,执行销毁 timer 的做法,这个办法,简单有效:```objectivec// 销毁timer[self.timer invalidate];self.timer = nil;
解决方案2:打破循环强引用
思路1:是将 target 参数传入的 self 使用 weak 修饰。代码如下:
__weak typeof(self) weakSelf = self;self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(timerAction) userInfo:nil repeats:YES];[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

但是根据源码中,可以得知,无论target 是否有 weak 修饰,都会retain(target), 形成强引用。 所以这个方案无效。不能打破循环引用
思路2: VC 对 Timer 不强持有,如下图所示:
这样也是存在问题的,Runloop 强持有 Timer, 导致Timer 无法释放; Timer 强持有 VC, 导致VC无法释放
思路3:借助 NSProxy 打破循环引用。
NSProxy 是一个OC 提供的代理类,可以把代理的消息转发给真实的对象(还有一个功能是实现多继承)。但是它是一个抽象类,只定义了一些方法,没有自己的初始化方法及转发消息的实现。需要子类来实现具体的方法。YYWeakProxy 就是一个很好的实现,我们可以直接使用它。
- 将 VC 使用 YYWeakProxy 对象包装,YYWeakProxy 内部对 VC 是弱引用。这样就没有什么对象在强持有 VC,
返回后 VC 释放, 执行 dealloc 回调释放Timer. 这样 VC 对Timer 的强引用,和runloop 对Timer 的强引用都可以在 invalidate 方法中释放掉。
如下图所示:

代码如下: ```objectivecimport “TimerViewController.h”
import “YYWeakProxy.h”
@interface TimerViewController () @property (nonatomic, strong) NSTimer * timer; @end
@implementation TimerViewController
(void)viewDidLoad { [super viewDidLoad]; YYWeakProxy * weakProxy = [YYWeakProxy proxyWithTarget:self]; self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakProxy selector:@selector(timerAction) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes]; }
(void)timerAction{}
(void)dealloc{ [self.timer invalidate]; self.timer = nil; NSLog(@”** dealloc *“); }
@end
**NSProxy源码:**```objectivec@interface NSProxy <NSObject> {Class isa;}+ (id)alloc;+ (id)allocWithZone:(nullable NSZone *)zone NS_AUTOMATED_REFCOUNT_UNAVAILABLE;+ (Class)class;- (void)forwardInvocation:(NSInvocation *)invocation;- (nullable NSMethodSignature *)methodSignatureForSelector:(SEL)sel NS_SWIFT_UNAVAILABLE("NSInvocation and related APIs not available");- (void)dealloc;- (void)finalize;@property (readonly, copy) NSString *description;@property (readonly, copy) NSString *debugDescription;+ (BOOL)respondsToSelector:(SEL)aSelector;- (BOOL)allowsWeakReference API_UNAVAILABLE(macos, ios, watchos, tvos);- (BOOL)retainWeakReference API_UNAVAILABLE(macos, ios, watchos, tvos);// - (id)forwardingTargetForSelector:(SEL)aSelector;@end
YYWeakProxy 源码:
#import <Foundation/Foundation.h>NS_ASSUME_NONNULL_BEGIN@interface YYWeakProxy : NSProxy@property (nullable, nonatomic, weak, readonly) id target;- (instancetype)initWithTarget:(id)target;+ (instancetype)proxyWithTarget:(id)target;@endNS_ASSUME_NONNULL_END#import "YYWeakProxy.h"@implementation YYWeakProxy- (instancetype)initWithTarget:(id)target {_target = target;return self;}+ (instancetype)proxyWithTarget:(id)target {return [[YYWeakProxy alloc] initWithTarget:target];}- (id)forwardingTargetForSelector:(SEL)selector {return _target;}- (void)forwardInvocation:(NSInvocation *)invocation {void *null = NULL;[invocation setReturnValue:&null];}- (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {return [NSObject instanceMethodSignatureForSelector:@selector(init)];}- (BOOL)respondsToSelector:(SEL)aSelector {return [_target respondsToSelector:aSelector];}- (BOOL)isEqual:(id)object {return [_target isEqual:object];}- (NSUInteger)hash {return [_target hash];}- (Class)superclass {return [_target superclass];}- (Class)class {return [_target class];}- (BOOL)isKindOfClass:(Class)aClass {return [_target isKindOfClass:aClass];}- (BOOL)isMemberOfClass:(Class)aClass {return [_target isMemberOfClass:aClass];}- (BOOL)conformsToProtocol:(Protocol *)aProtocol {return [_target conformsToProtocol:aProtocol];}- (BOOL)isProxy {return YES;}- (NSString *)description {return [_target description];}- (NSString *)debugDescription {return [_target debugDescription];}@end
