1.1 NSTimer 与运行循环的关系

Timer 初始化部分源码如下:
timer 初始化时,会对传入的target 和 info 执行 retain , 即使传入的是一个weak 修饰的对象,也会是强引用。

  1. - (id) initWithFireDate: (NSDate*)fd
  2. interval: (NSTimeInterval)ti
  3. target: (id)object
  4. selector: (SEL)selector
  5. userInfo: (id)info
  6. repeats: (BOOL)f
  7. {
  8. ...
  9. _target = RETAIN(object);
  10. _selector = selector;
  11. _info = RETAIN(info);
  12. ...
  13. }

运行循环加入timer 的部分源码:
运行循环强持有一个 timers 数组,在添加 timer 的时候,加到了timers 数组中,所以运行循环强持有timer。

  1. - (void) addTimer: (NSTimer*)timer
  2. forMode: (NSString*)mode
  3. {
  4. GSRunLoopCtxt *context;
  5. GSIArray timers;
  6. unsigned i;
  7. ...
  8. context = NSMapGet(_contextMap, mode);
  9. ...
  10. timers = context->timers;
  11. ...
  12. GSIArrayAddItem(timers, (GSIArrayItem)((id)timer));
  13. ...
  14. }

总结:定时器需要依赖运行循环上才能执行, 且被运行循环强持有。

1.2 NSTimer 的使用

NSTimer 提供6个类方法,和2个对象方法.

1. 自动加入运行循环的类方法

以下方法是自动加入到当前的运行循环且mode为kCFRunLoopDefaultMode

  1. + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
  2. + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;
  3. + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;

2. 需要手动加入运行循环的类方法

  1. + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)interval repeats:(BOOL)repeats block:(void (^)(NSTimer *timer))block;
  2. + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti invocation:(NSInvocation *)invocation repeats:(BOOL)yesOrNo;
  3. + (NSTimer *)timerWithTimeInterval:(NSTimeInterval)ti target:(id)aTarget selector:(SEL)aSelector userInfo:(id)userInfo repeats:(BOOL)yesOrNo;

使用方法:

  1. /**
  2. * 打开网络请求访问超时定时器
  3. */
  4. - (void)startTimer {
  5. if (!self.timeoutTimer) {
  6. self.timeoutTimer = [NSTimer timerWithTimeInterval:DEFAULT_TIMEOUT_INTERVAL target:self selector:@selector(checkTaskStatus) userInfo:nil repeats:NO];
  7. [self.runloop addTimer:self.timeoutTimer forMode:NSRunLoopCommonModes];
  8. }
  9. }
  10. /**
  11. * 关闭网络请求访问超时定时器
  12. */
  13. - (void)stopTimer {
  14. if (self.timeoutTimer) {
  15. [self.timeoutTimer invalidate];
  16. self.timeoutTimer = nil;
  17. }
  18. }

3. 需要手动加入运行循环的对象方法

  1. - (instancetype)initWithFireDate:(NSDate *)date interval:(NSTimeInterval)ti target:(id)t selector:(SEL)s userInfo:(id)ui repeats:(BOOL)rep;
  2. - (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;

  1. <a name="cH7hc"></a>
  2. ### 2. Timer 与 VC 的循环引用问题
  3. 在我们上面的写法儿中,
  4. - VC 持有 Timer, 对 Timer 是强引用
  5. - Timer 的 Target 设置的是 VC ,Timer 对 VC 也是强引用,直到 **Timer invalidate, Timer 内部才会释放对 Target 和 info 的强持有。**
  6. - 同时,Timer 被添加到了Runloop, 那么 Runloop 也会强引用 Timer。
  7. - repeats 为 NO 的在执行一次后,会自动从运行循环移除。
  8. - repeats 为 YES 的,直到 **Timer invalidate, 才会从运行循环中移除**
  9. 三者间的关系如下图所示:<br />![image.png](https://cdn.nlark.com/yuque/0/2021/png/94660/1622647558938-e202dca7-acb9-40dd-bfee-78d52c9d2588.png#clientId=u8342f8f6-a53e-4&from=paste&height=229&id=VcggS&originHeight=458&originWidth=1120&originalType=binary&size=44679&status=done&style=none&taskId=ua1ccfe0a-9c41-4e03-834d-b998a48edfa&width=560)<br />这样就出现了**循环引用**,产生 VC dealloc 无法执行,无法释放的问题。
  10. <a name="ykw7H"></a>
  11. #### 解决方案1:返回时销毁Timer
  12. 比较常用的做法是在点击返回按钮的时候,执行销毁 timer 的做法,这个办法,简单有效:
  13. ```objectivec
  14. // 销毁timer
  15. [self.timer invalidate];
  16. self.timer = nil;

image.png

解决方案2:打破循环强引用

思路1:是将 target 参数传入的 self 使用 weak 修饰。代码如下:

  1. __weak typeof(self) weakSelf = self;
  2. self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(timerAction) userInfo:nil repeats:YES];
  3. [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];

image.png
但是根据源码中,可以得知,无论target 是否有 weak 修饰,都会retain(target), 形成强引用。 所以这个方案无效。不能打破循环引用

思路2: VC 对 Timer 不强持有,如下图所示:
image.png
这样也是存在问题的,Runloop 强持有 Timer, 导致Timer 无法释放; Timer 强持有 VC, 导致VC无法释放

思路3:借助 NSProxy 打破循环引用。
NSProxy 是一个OC 提供的代理类,可以把代理的消息转发给真实的对象(还有一个功能是实现多继承)。但是它是一个抽象类,只定义了一些方法,没有自己的初始化方法及转发消息的实现。需要子类来实现具体的方法。YYWeakProxy 就是一个很好的实现,我们可以直接使用它。

  • 将 VC 使用 YYWeakProxy 对象包装,YYWeakProxy 内部对 VC 是弱引用。这样就没有什么对象在强持有 VC,
  • 返回后 VC 释放, 执行 dealloc 回调释放Timer. 这样 VC 对Timer 的强引用,和runloop 对Timer 的强引用都可以在 invalidate 方法中释放掉。

    如下图所示:
    image.png
    代码如下: ```objectivec

    import “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

  1. **NSProxy源码:**
  2. ```objectivec
  3. @interface NSProxy <NSObject> {
  4. Class isa;
  5. }
  6. + (id)alloc;
  7. + (id)allocWithZone:(nullable NSZone *)zone NS_AUTOMATED_REFCOUNT_UNAVAILABLE;
  8. + (Class)class;
  9. - (void)forwardInvocation:(NSInvocation *)invocation;
  10. - (nullable NSMethodSignature *)methodSignatureForSelector:(SEL)sel NS_SWIFT_UNAVAILABLE("NSInvocation and related APIs not available");
  11. - (void)dealloc;
  12. - (void)finalize;
  13. @property (readonly, copy) NSString *description;
  14. @property (readonly, copy) NSString *debugDescription;
  15. + (BOOL)respondsToSelector:(SEL)aSelector;
  16. - (BOOL)allowsWeakReference API_UNAVAILABLE(macos, ios, watchos, tvos);
  17. - (BOOL)retainWeakReference API_UNAVAILABLE(macos, ios, watchos, tvos);
  18. // - (id)forwardingTargetForSelector:(SEL)aSelector;
  19. @end

YYWeakProxy 源码:

  1. #import <Foundation/Foundation.h>
  2. NS_ASSUME_NONNULL_BEGIN
  3. @interface YYWeakProxy : NSProxy
  4. @property (nullable, nonatomic, weak, readonly) id target;
  5. - (instancetype)initWithTarget:(id)target;
  6. + (instancetype)proxyWithTarget:(id)target;
  7. @end
  8. NS_ASSUME_NONNULL_END
  9. #import "YYWeakProxy.h"
  10. @implementation YYWeakProxy
  11. - (instancetype)initWithTarget:(id)target {
  12. _target = target;
  13. return self;
  14. }
  15. + (instancetype)proxyWithTarget:(id)target {
  16. return [[YYWeakProxy alloc] initWithTarget:target];
  17. }
  18. - (id)forwardingTargetForSelector:(SEL)selector {
  19. return _target;
  20. }
  21. - (void)forwardInvocation:(NSInvocation *)invocation {
  22. void *null = NULL;
  23. [invocation setReturnValue:&null];
  24. }
  25. - (NSMethodSignature *)methodSignatureForSelector:(SEL)selector {
  26. return [NSObject instanceMethodSignatureForSelector:@selector(init)];
  27. }
  28. - (BOOL)respondsToSelector:(SEL)aSelector {
  29. return [_target respondsToSelector:aSelector];
  30. }
  31. - (BOOL)isEqual:(id)object {
  32. return [_target isEqual:object];
  33. }
  34. - (NSUInteger)hash {
  35. return [_target hash];
  36. }
  37. - (Class)superclass {
  38. return [_target superclass];
  39. }
  40. - (Class)class {
  41. return [_target class];
  42. }
  43. - (BOOL)isKindOfClass:(Class)aClass {
  44. return [_target isKindOfClass:aClass];
  45. }
  46. - (BOOL)isMemberOfClass:(Class)aClass {
  47. return [_target isMemberOfClass:aClass];
  48. }
  49. - (BOOL)conformsToProtocol:(Protocol *)aProtocol {
  50. return [_target conformsToProtocol:aProtocol];
  51. }
  52. - (BOOL)isProxy {
  53. return YES;
  54. }
  55. - (NSString *)description {
  56. return [_target description];
  57. }
  58. - (NSString *)debugDescription {
  59. return [_target debugDescription];
  60. }
  61. @end