iOS 中的 NSTimer

移动开发 iOS
前阵子在整理公司项目的时候,发现老代码在使用 NSTimer 时出现了内存泄露。然后整理了一些 NSTimer 的相关内容。比较简单,各位见笑啦。

[[139776]]

前阵子在整理公司项目的时候,发现老代码在使用 NSTimer 时出现了内存泄露。然后整理了一些 NSTimer 的相关内容。比较简单,各位见笑啦。

NSTimer

fire

我们先用 NSTimer 来做个简单的计时器,每隔5秒钟在控制台输出 Fire 。比较想当然的做法是这样的:

  1. @interface DetailViewController () 
  2. @property (nonatomic, weak) NSTimer *timer; 
  3. @end 
  4. @implementation DetailViewController 
  5. - (IBAction)fireButtonPressed:(id)sender { 
  6. _timer = [NSTimer scheduledTimerWithTimeInterval:3.0f 
  7. target:self 
  8. selector:@selector(timerFire:) 
  9. userInfo:nil 
  10. repeats:YES]; 
  11. [_timer fire]; 
  12. -(void)timerFire:(id)userinfo { 
  13. NSLog(@"Fire"); 
  14. @end 

运行之后确实在控制台每隔3秒钟输出一次 Fire ,然而当我们从这个界面跳转到其他界面的时候却发现:控制台还在源源不断的输出着 Fire 。看来 Timer 并没有停止。

 

  1. invalidate 
  2.  
  3. 既然没有停止,那我们在 DemoViewController 的 dealloc 里加上 invalidate 的方法: 
  4.  
  5. -(void)dealloc { 
  6. [_timer invalidate]; 
  7. NSLog(@"%@ dealloc", NSStringFromClass([self class])); 

 

再次运行,还是没有停止。原因是 Timer 添加到 Runloop 的时候,会被 Runloop 强引用:
 

  1. Note in particular that run loops maintain strong references to their timers, so you don’t have to maintain your own strong reference to a timer after you have added it to a run loop. 

然后 Timer 又会有一个对 Target 的强引用(也就是 self ):

  1. Target is the object to which to send the message specified by aSelector when the timer fires. The timer maintains a strong reference to target until it (the timer) is invalidated. 

也就是说 NSTimer 强引用了 self ,导致 self 一直不能被释放掉,所以也就走不到 self 的 dealloc 里。

既然如此,那我们可以再加个 invalidate 按钮:

  1. - (IBAction)invalidateButtonPressed:(id)sender { 
  2. [_timer invalidate]; 

嗯这样就可以了。(在 SOF 上有人说该在 invalidate 之后执行 _timer = nil ,未能理解为什么,如果你知道原因可以告诉我:)

在 invalidate 方法的文档里还有这这样一段话:

 

  1. You must send this message from the thread on which the timer was installed. If you send this message from another thread, the input source associated with the timer may not be removed from its run loop, which could prevent the thread from exiting properly. 

NSTimer 在哪个线程创建就要在哪个线程停止,否则会导致资源不能被正确的释放。看起来各种坑还不少。

dealloc

那么问题来了:如果我就是想让这个 NSTimer 一直输出,直到 DemoViewController 销毁了才停止,我该如何让它停止呢?

NSTimer 被 Runloop 强引用了,如果要释放就要调用 invalidate 方法。

但是我想在 DemoViewController 的 dealloc 里调用 invalidate 方法,但是 self 被 NSTimer 强引用了。

所以我还是要释放 NSTimer 先,然而不调用 invalidate 方法就不能释放它。

然而你不进入到 dealloc 方法里我又不能调用 invalidate 方法。

嗯…

HWWeakTimer

weakSelf

问题的关键就在于 self 被 NSTimer 强引用了,如果我们能打破这个强引用问题自然而然就解决了。所以一个很简单的想法就是:weakSelf:

  1. __weak typeof(self) weakSelf = self; 
  2. _timer = [NSTimer scheduledTimerWithTimeInterval:3.0f 
  3. target:weakSelf 
  4. selector:@selector(timerFire:) 
  5. userInfo:nil 
  6. repeats:YES]; 

然而这并没有什么卵用,这里的 __weak 和 __strong ***的区别就是:如果在这两行代码执行的期间 self 被释放了, NSTimer 的 target 会变成 nil 。

target

既然没办法通过 __weak 把 self 抽离出来,我们可以造个假的 target 给 NSTimer 。这个假的 target 类似于一个中间的代理人,它做的***的工作就是挺身而出接下了 NSTimer 的强引用。类声明如下:

  1. @interface HWWeakTimerTarget : NSObject 
  2. @property (nonatomic, weak) id target; 
  3. @property (nonatomic, assign) SEL selector; 
  4. @property (nonatomic, weak) NSTimer* timer; 
  5. @end 
  6. @implementation HWWeakTimerTarget 
  7. - (void) fire:(NSTimer *)timer { 
  8. if(self.target) { 
  9. [self.target performSelector:self.selector withObject:timer.userInfo]; 
  10. else { 
  11. [self.timer invalidate]; 
  12. @end 

然后我们再封装个假的 scheduledTimerWithTimeInterval 方法,但是在调用的时候已经偷梁换柱了:

  1. + (NSTimer *) scheduledTimerWithTimeInterval:(NSTimeInterval)interval 
  2. target:(id)aTarget 
  3. selector:(SEL)aSelector 
  4. userInfo:(id)userInfo 
  5. repeats:(BOOL)repeats { 
  6. HWWeakTimerTarget* timerTarget = [[HWWeakTimerTarget alloc] init]; 
  7. timerTarget.target = aTarget; 
  8. timerTarget.selector = aSelector; 
  9. timerTarget.timer = [NSTimer scheduledTimerWithTimeInterval:interval 
  10. target:timerTarget 
  11. selector:@selector(fire:) 
  12. userInfo:userInfo 
  13. repeats:repeats]; 
  14. return timerTarget.timer; 

再次运行,问题解决。

block

如果能用 block 来调用 NSTimer 那岂不是更好了。我们可以这样来实现:

  1. + (NSTimer *)scheduledTimerWithTimeInterval:(NSTimeInterval)interval 
  2. block:(HWTimerHandler)block 
  3. userInfo:(id)userInfo 
  4. repeats:(BOOL)repeats { 
  5. return [self scheduledTimerWithTimeInterval:interval 
  6. target:self 
  7. selector:@selector(_timerBlockInvoke:) 
  8. userInfo:@[[block copy], userInfo] 
  9. repeats:repeats]; 
  10. + (void)_timerBlockInvoke:(NSArray*)userInfo { 
  11. HWTimerHandler block = userInfo[0]; 
  12. id info = userInfo[1]; 
  13. // or `!block ?: block();` @sunnyxx 
  14. if (block) { 
  15. block(info); 

这样我们就可以直接在 block 里写相关逻辑了:

  1. - (IBAction)fireButtonPressed:(id)sender { 
  2. _timer = [HWWeakTimer scheduledTimerWithTimeInterval:3.0f block:^(id userInfo) { 
  3. NSLog(@"%@", userInfo); 
  4. } userInfo:@"Fire" repeats:YES]; 
  5. [_timer fire]; 

嗯就是这样。

More

把上面的的代码简单的封装到了 HWWeakTimer 中,欢迎试用。

责任编辑:chenqingxiang 来源: CocoaChina
相关推荐

2017-05-04 20:15:51

iOSNSTimer循环引用

2013-04-28 10:53:44

iOS开发NSDate计算日期计算

2015-03-18 09:29:12

iOS开发争议

2015-07-08 16:46:05

iOS键盘

2015-10-20 11:22:34

iOS开发Git

2014-05-09 11:23:29

iOS移动互联网

2014-04-23 14:40:06

iOS开发KVO内部实现

2013-07-22 13:48:55

iOS开发ASIHTTPRequ使用Cookie

2013-06-14 13:50:28

iOS开发移动开发警告视图

2014-02-19 09:59:52

iOS开发Html解析

2013-01-06 09:52:43

SQLite

2013-04-09 16:04:06

iOS开发SQLite知识总结

2017-01-10 13:33:51

iOS编程throttle

2012-07-18 15:30:58

iOS交互原型

2020-10-12 09:50:10

iOS 14苹果功能

2013-04-01 10:49:51

iOS开发sqlite数据库

2013-03-27 11:33:32

iOS开发iOSjson解析方式

2011-12-01 09:25:33

iOS 5移动开发iOS

2014-04-23 13:30:23

类簇iOS开发

2014-03-04 15:28:32

iOS开发消息传递机制
点赞
收藏

51CTO技术栈公众号