美文网首页
NSTimer学习笔记

NSTimer学习笔记

作者: _Lily | 来源:发表于2015-12-31 11:23 被阅读67次

一、NSTimer认识

NSTimer其实是将一个监听加入到系统的RunLoop中去,当系统runloop到如何timer条件的循环时,会调用timer一次,当timer执行完,也就是回调函数执行之后,timer会再一次的将自己加入到runloop中去继续监听。

一个timer对象在同一时间只能够被注册到一个runloop中,尽管在这个runloop中它能够被添加到多个runloop模式中去。

二、NSTimer使用

有以下三种初始化方法:

使用scheduledTimerWithTimeInterval: invocation: repeats:或者scheduledTimerWithTimeInterval: target: selector: userInfo: repeats:这两个类方法创建一个timer并把它指定到一个默认的runloop模式中

使用timerWithTimeInterval: invocation: repeats:或者timerWithTimeInterval: target: selector: userInfo: repeats: 这两个类方法创建一个timer的对象 (当创建之后,你必须手动的调用NSRunLoop下对应的方法addTimer:forMode:去将它制定到一个runloop模式中)。

使用initWithFireDate: interval: target: selector: userInfo: repeats: 方法分配并创建一个NSTimer的实例(当创建之后,你必须手动的调用NSRunLoop下对应的方法addTimer:forMode:去将它制定到一个runloop模式中)。

[timer fire];//可以通过fire这个方法去触发timer,即使timer的firing time没有到达

注意:不用scheduled方式初始化的,需要手动addTimer: forMode:  将timer添加到一个runloop中。而scheduled的初始化方法将以默认mode直接添加到当前的runloop中。

以下是一个采用scheduled的初始化方法的60秒倒计时定时器的初始化:

_countDownTimer= [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timeFireMethod) userInfo:nil repeats:YES];

将计数器的repeats设置为YES时,self的引用计数会加1。因此可能会导致self(即viewController)不能release,所以,必须在viewWillAppear的时候,将计数器timer停止,否则可能会导致内存泄露。

停止的方法为:[self.countDownTimer invalidate];

- (void)invalidate是唯一一个可以将计时器从runloop中移出的方法。

注意:停止timer的运行,一定要将timer赋空,否则还是没有释放!

相关文章

  • NSTimer学习笔记

    1. 什么是NSTimer   官方的解释“A timer provides a way to perform a...

  • NSTimer学习笔记

    NSTimer是iOS最常用的定时器工具之一,在使用的时候常常会遇到各种各样的问题,最常见的是内存泄漏,通常我们使...

  • NSTimer学习笔记

    一、NSTimer认识 NSTimer其实是将一个监听加入到系统的RunLoop中去,当系统runloop到如何t...

  • iOS 在子线程中NSTimer的启动和关闭

    之前在项目中遇见了一个问题,在子线程中如何开启NSTimer和取消NSTimer。现在总结一下,当做自己的笔记。 ...

  • iOS 在子线程中NSTimer的启动和关闭

    之前在项目中遇见了一个问题,在子线程中如何开启NSTimer和取消NSTimer。现在总结一下,当做自己的笔记。 ...

  • iOS中的计时器

    一、NSTimer 创建方法 1 NSTimer *timer = [NSTimer scheduledTimer...

  • NSTimer

    创建NSTimer 创建NSTimer的常用方法是: + (NSTimer *)scheduledTimerWit...

  • iOS 延时

    1 NSTimer //1秒后执行 NSTimer *timer = [NSTimer timerWithTim...

  • iOS 获取网络流量

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:...

  • 时间倒计时

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:...

网友评论

      本文标题:NSTimer学习笔记

      本文链接:https://www.haomeiwen.com/subject/kqbihttx.html