iOS中的NSTimer定时器的初步使用解析

所属分类: 软件编程 / IOS 阅读数: 1725
收藏 0 赞 0 分享

创建一个定时器(NSTimer)

- (void)viewDidLoad {
  [super viewDidLoad];
  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(actionTimer:) userInfo:nil repeats:YES];
}

- (void)actionTimer:(NSTimer *)timer
{

}

NSTimer默认运行在default mode下,default mode几乎包括所有输入源(除NSConnection) NSDefaultRunLoopMode模式。

actionTimer方法会每隔1s中被调用一次。NSTimer使用起来是不是非常简单。这是NSTimer比较初级的应用。

当主界面被滑动时NSTimer失效了

主界面被滑动是什么意思呢?就是说主界面有UITableView或者UIScrollView,滑动UITableView或者UIScrollView。这个时候NSTimer失效了。

我们来写一个demo,在一个有UITableView的UIViewController上启动定时器,每1s数字加1,并将这个数字显示在UILabel上面.

- (void)viewDidLoad {
  [super viewDidLoad];
  [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(actionTimer:) userInfo:nil repeats:YES];
}

- (void)actionTimer:(NSTimer *)timer
{
  self.number++;
  self.label.text = [NSString stringWithFormat:@"%d",self.number];
  NSLog(@"%d",self.number);
}

关于UITableView和UILabel的创建我省去了。详细的代码可以点击这里下载:iOSStrongDemo,iOSStrongDemo我会不断更新,大家在github上star一下。

这样当用户在拖动UITableView处于UITrackingRunLoopMode时,NSTimer就失效了,不能fire。self.label上的数字也就无法更新。

修改NSTimer的run loop

解决方法就是将其加入到UITrackingRunLoopMode模式或NSRunLoopCommonModes模式中。

[[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];

或者

[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

NSRunLoopCommonModes:是一个模式集合,当绑定一个事件源到这个模式集合的时候就相当于绑定到了集合内的每一个模式。

fire

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

@interface DetailViewController ()
@property (nonatomic, weak) NSTimer *timer;
@end

@implementation DetailViewController
- (IBAction)fireButtonPressed:(id)sender {
  _timer = [NSTimer scheduledTimerWithTimeInterval:3.0f
                       target:self
                      selector:@selector(timerFire:)
                      userInfo:nil
                       repeats:YES];
  [_timer fire];
}

-(void)timerFire:(id)userinfo {
  NSLog(@"Fire");
}
@end

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

invalidate

既然没有停止,那我们在 DemoViewController 的 dealloc 里加上 invalidate 的方法:

-(void)dealloc {
  [_timer invalidate];
  NSLog(@"%@ dealloc", NSStringFromClass([self class]));
}

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

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 ):

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 按钮:

- (IBAction)invalidateButtonPressed:(id)sender {
  [_timer invalidate];
}

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

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

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 方法。
  • 嗯…


更多精彩内容其他人还在看

iOS开发笔记--详解UILabel的相关属性设置

这篇文章主要介绍了iOS开发笔记--详解UILabel的相关属性设置,对初学者具有一定的参考价值,有需要的可以了解一下。
收藏 0 赞 0 分享

iOS中获取系统相册中的图片实例

这篇文章主要介绍了iOS中获取系统相册中的图片实例,具有一定的参考价值没有需要的朋友可以了解一下。
收藏 0 赞 0 分享

iOS 检测网络状态的两种方法

一般有Reachability和AFNetworking监测两种方式,都是第三方的框架,下文逐一详细给大家讲解,感兴趣的朋友一起看看吧
收藏 0 赞 0 分享

IOS 性能优化中离屏渲染

本文主要介绍了IOS 性能优化中离屏渲染的资料,提供了几种方法讲解了优化,有需要的小伙伴可以参考下
收藏 0 赞 0 分享

iOS获取当前设备型号等信息(全)包含iPhone7和iPhone7P

这篇文章主要介绍了iOS获取当前设备型号设备信息的总结包含iPhone7和iPhone7P,包括ios7之前之后的获取方式,本文接的非常详细,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

iOS实现爆炸的粒子效果示例代码

之前在网上看到了一个Android实现的爆炸效果,感觉非常不错,所以自己尝试用iOS来实现下效果,现在将实现的过程、原理以及遇到的问题分享给大家,有需要的朋友们可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

iOS毕业设计之天气预报App

这篇文章主要为大家详细介绍了iOS毕业设计之天气预报App,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

iOS轻点、触摸和手势代码开发

这篇文章主要为大家详细介绍了iOS轻点、触摸和手势代码开发,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

iOS 实现多代理的方法及实例代码

这篇文章主要介绍了iOS 实现多代理的方法及实例代码的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

iOS文字渐变色效果的实现方法

在大家日常开发iOS的过程中,可能会遇到要实现文字渐变色的效果,这篇文章文章通过示例代码和详细的步骤介绍了如何利用iOS实现文字渐变色的效果,实现后的很不错,感兴趣的朋友们下面来一起看看吧。
收藏 0 赞 0 分享
查看更多