NSTimer 使用小结
目录
1. NSRunLoopCommonModes和Timer
当使用NSTimer
的scheduledTimerWithTimeInterval
方法时。事实上此时Timer会被加入到当前线程的Run Loop中,且模式是默认的NSDefaultRunLoopMode
。而如果当前线程就是主线程,也就是UI线程时,某些UI事件,比如UIScrollView
的拖动操作,会将Run Loop切换成NSEventTrackingRunLoopMode
模式,在这个过程中,默认的NSDefaultRunLoopMode
模式中注册的事件是不会被执行的。也就是说,此时使用scheduledTimerWithTimeInterval
添加到Run Loop中的Timer就不会执行。
所以为了设置一个不被UI干扰的Timer,我们需要手动创建一个Timer,然后使用NSRunLoop
的addTimer:forMode:
方法来把Timer按照指定模式加入到Run Loop中。这里使用的模式是:NSRunLoopCommonModes
,这个模式等效于NSDefaultRunLoopMode
和NSEventTrackingRunLoopMode
的结合。(参考Apple文档)
参考代码:
- (void)viewDidLoad
{
[super viewDidLoad]; NSLog(@"主线程 %@", [NSThread currentThread]);
//创建Timer
NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(timer_callback) userInfo:nil repeats:YES];
//使用NSRunLoopCommonModes模式,把timer加入到当前Run Loop中。
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
} //timer的回调方法
- (void)timer_callback
{
NSLog(@"Timer %@", [NSThread currentThread]);
}
输出:
主线程 <NSThread: 0x71501e0>{name = (null), num = 1}
Timer <NSThread: 0x71501e0>{name = (null), num = 1}
Timer <NSThread: 0x71501e0>{name = (null), num = 1}
Timer <NSThread: 0x71501e0>{name = (null), num = 1}
2. NSThread和Timer
上面讲的NSRunLoopCommonModes
和Timer中有一个问题,这个Timer本质上是在当前线程的Run Loop中循环执行的,因此Timer的回调方法不是在另一个线程的。那么怎样在真正的多线程环境下运行一个Timer呢?
可以先试试NSThread
。同上,我们还是会把Timer加到Run Loop中,只不过这个是在另一个线程中,因此我们需要手动执行Run Loop(通过NSRunLoop
的run
方法),同时注意在新的线程执行中加入@autoreleasepool
。
完整代码如下:
- (void)viewDidLoad
{
[super viewDidLoad]; NSLog(@"主线程 %@", [NSThread currentThread]); //创建并执行新的线程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(newThread) object:nil];
[thread start];
} - (void)newThread
{
@autoreleasepool
{
//在当前Run Loop中添加timer,模式是默认的NSDefaultRunLoopMode
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(timer_callback) userInfo:nil repeats:YES];
//开始执行新线程的Run Loop
[[NSRunLoop currentRunLoop] run];
}
} //timer的回调方法
- (void)timer_callback
{
NSLog(@"Timer %@", [NSThread currentThread]);
}
输出:
主线程 <NSThread: 0x7118800>{name = (null), num = 1}
Timer <NSThread: 0x715c2e0>{name = (null), num = 3}
Timer <NSThread: 0x715c2e0>{name = (null), num = 3}
Timer <NSThread: 0x715c2e0>{name = (null), num = 3}
3. GCD中的Timer
GCD中的Timer应该是最灵活的,而且是多线程的。GCD中的Timer是靠Dispatch Source来实现的。
因此先需要声明一个dispatch_source_t
本地变量:
@interface ViewController ()
{
dispatch_source_t _timer;
}
接着通过dispatch_source_create
函数来创建一个专门的Dispatch Source,接着通过dispatch_source_set_timer
函数来设置Timer的参数,注意这里的时间参数有些蛋疼。
开始时间的类型是dispatch_time_t
,最好用dispatch_time
或者dispatch_walltime
函数来创建dispatch_time_t
对象。如果需要Timer立即执行,可以传入dispatch_time(DISPATCH_TIME_NOW, 0)
。
internal
和leeway
参数分别表示Timer的间隔时间和精度。类型都是uint64_t
。间隔时间的单位竟然是纳秒。可以借助预定义的NSEC_PER_SEC
宏,比如如果间隔时间是两秒的话,那interval
参数就是:2 * NSEC_PER_SEC
。
leeway
就是精度参数,代表系统可以延时的时间间隔,最高精度当然就传0。
然后通过dispatch_source_set_event_handler
函数来设置Dispatch Source的事件回调,这里当然是使用Block了。
最后所有dispatch_source_t
创建后默认都是暂停状态的,所以必须通过dispatch_resume
函数来开始事件监听。这里就代表着开始Timer。
完整代码:
NSLog(@"主线程 %@", [NSThread currentThread]);
//间隔还是2秒
uint64_t interval = 2 * NSEC_PER_SEC;
//创建一个专门执行timer回调的GCD队列
dispatch_queue_t queue = dispatch_queue_create("my queue", 0);
//创建Timer
_timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
//使用dispatch_source_set_timer函数设置timer参数
dispatch_source_set_timer(_timer, dispatch_time(DISPATCH_TIME_NOW, 0), interval, 0);
//设置回调
dispatch_source_set_event_handler(_timer, ^()
{
NSLog(@"Timer %@", [NSThread currentThread]);
});
//dispatch_source默认是Suspended状态,通过dispatch_resume函数开始它
dispatch_resume(_timer);
输出:
主线程 <NSThread: 0x711fab0>{name = (null), num = 1}
Timer <NSThread: 0x713a380>{name = (null), num = 3}
Timer <NSThread: 0x713a380>{name = (null), num = 3}
Timer <NSThread: 0x713a380>{name = (null), num = 3}
NSTimer 使用小结的更多相关文章
- iOS - CADisplayLink与NSTimer
一.CADisplayLink简介 CADisplayLink 是一个定时器对象可以让你的应用以与显示器的刷新界面相同的频率进行绘图. 应用如果想要创建 display link ,需要提供一个目标对 ...
- OC小结
#import <Foundation/Foundation.h>#import "Person.h"int main(int argc, const char * a ...
- 小结OC中Retain cycle(循环引用)
retain cycle 的产生 说到retain cycle,首先要提一下Objective-C的内存管理机制. 作为C语言的超集,Objective-C延续了C语言中手动管理内存的方式,但是区别于 ...
- Objective-C三种定时器CADisplayLink / NSTimer / GCD的使用
OC中的三种定时器:CADisplayLink.NSTimer.GCD 我们先来看看CADiskplayLink, 点进头文件里面看看, 用注释来说明下 @interface CADisplayLin ...
- 从零开始编写自己的C#框架(26)——小结
一直想写个总结,不过实在太忙了,所以一直拖啊拖啊,拖到现在,不过也好,有了这段时间的沉淀,发现自己又有了小小的进步.哈哈...... 原想框架开发的相关开发步骤.文档.代码.功能.部署等都简单的讲过了 ...
- Python自然语言处理工具小结
Python自然语言处理工具小结 作者:白宁超 2016年11月21日21:45:26 目录 [Python NLP]干货!详述Python NLTK下如何使用stanford NLP工具包(1) [ ...
- java单向加密算法小结(2)--MD5哈希算法
上一篇文章整理了Base64算法的相关知识,严格来说,Base64只能算是一种编码方式而非加密算法,这一篇要说的MD5,其实也不算是加密算法,而是一种哈希算法,即将目标文本转化为固定长度,不可逆的字符 ...
- iOS--->微信支付小结
iOS--->微信支付小结 说起支付,除了支付宝支付之外,微信支付也是我们三方支付中最重要的方式之一,承接上面总结的支付宝,接下来把微信支付也总结了一下 ***那么首先还是由公司去创建并申请使用 ...
- iOS 之UITextFiled/UITextView小结
一:编辑被键盘遮挡的问题 参考自:http://blog.csdn.net/windkisshao/article/details/21398521 1.自定方法 ,用于移动视图 -(void)mov ...
随机推荐
- 刷题总结——bzoj1725(状压dp)
题目: 题目描述 Farmer John 新买了一块长方形的牧场,这块牧场被划分成 N 行 M 列(1<=M<=12; 1<=N<=12),每一格都是一块正方形的土地. FJ ...
- N*N数码问题
奇数码问题 时间限制: 1 Sec 内存限制: 128 MB 题目描述 你一定玩过八数码游戏,它实际上是在一个3*3的网格中进行的,1个空格和1~8这8个数字恰好不重不漏地分布在这3*3的网格中. ...
- miller_rabin + pollard_rho模版
#include<stdio.h> #include<stdlib.h> #include<time.h> #include<math.h> #incl ...
- Scrapy学习-3-Request回调巧用
基于twisted的异步回调 使得页面爬取有阶段性和连续性 from scrapy.http import Request from urllib import parse def parse(sel ...
- codeforces 1051 F
多源点最短路. 但是有限制,m - n <= 20,边数 - 点数 <= 20, 所以这个图非常的稀疏. 任意提取出一个生成树出来,LCA处理任意两点最短路. 然后再去遍历那些多余出来的点 ...
- LeetCode第一题以及时间复杂度的计算
问题描述:给定一组指定整数数组,找出数组中加和等于特定数的两个数. 函数(方法)twoSum返回这两个数的索引,index1必须小于index2. 另外:你可以假设一个数组只有一组解. 一个栗子: I ...
- Kafka windows下的安装
1. 安装JDK 1.1 安装文件:http://www.oracle.com/technetwork/java/javase/downloads/index.html 下载JDK1.2 安装完成后需 ...
- Obj-C, library with ARC code and warning - Method possibly missing a [super dealloc] call?
1 down vote favorite I'm adding the MKStoreKit to my app and I'm getting a warning, Method possibly ...
- centos的python2.6.x升级到python2.7.x方法;python2.6.x的版本就不要用了
python2.6.x的版本,现在使用的很多插件都不支持了.所以如果你的centos还是使用的2.6.x版本,不要犹豫,赶紧升级到2.7.x版本 1.所谓升级,就是再安装一个python2.7.x版本 ...
- Linux下Tomcat VM參数改动
不可行的方法 最初我直接改动catalina.sh, 将JAVA_OPTS变量加上了 -server -Xms1G -Xmx1G -XX:+UserG1GC 最初看起来没啥问题,可是当服务器运行几天后 ...