NSTimer与NSRunLoop的关系分析
NSTimer与NSRunLoop的关系分析
最近关于NSTimer和NSRunLoop的关系,做了一个小试验。代码地址:https://github.com/TianLibin/timerRunLoopTest.git
代码运行效果如下图所示:
本示例演示了四个定时器的效果以及界面操作对它们的影响。
前两个定时器,是在子线程中启动的:
- (void)subThread1
{
@autoreleasepool {
self.subThreadTimer1 = [NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(subThread1Fun:)
userInfo:nil
repeats:YES];
}
} - (void)subThread2
{
@autoreleasepool {
self.subThreadTimer2 = [NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(subThread2Fun:)
userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] run]; // 这行代码是两个定时器启动的不同之处
}
}
但是从运行效果看,第一个标签数字没有变化,一直是0,明显是定时器没有执行到。
两者的区别在于第二个多执行了一行代码:[[NSRunLoop currentRunLoop] run];
因为NSRunLoop在主线程中是默认运行的,子线程中默认不运行。所以在第一个定时器中,虽然设置了定时器,但出了该线程方法,runLoop默认停止了,异步的方法也就执行不到了。
第二个定时器,在线程中显示把runLoop运行起来了,它会一直运行下去,直到异步方法执行完毕。
下面比较第三,四两个定时器的效果:
- (void)startDefaultRunTimer
{
self.defaultRunTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(defaultRunFun:)
userInfo:nil
repeats:YES];
} - (void)startCommonRunTimer
{
self.commonRunTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f
target:self
selector:@selector(commonRunFun:)
userInfo:nil
repeats:YES];
// 下面一行代码是这两个定时器启动的不同之处
[[NSRunLoop currentRunLoop] addTimer:self.commonRunTimer forMode:NSRunLoopCommonModes];
}
从开始运行,这两个定时器没有什么不同之处。但是当我把手指按在下面左侧的滚动条上上下拖动滚动视图时,这时为了更清楚一看到区别,手指不要离开屏幕。能看到第三个标签数字停止变化,即定时器方法暂停执行了,松开手指后,数字继续变化。
两个定时器的区别在于这句话:[[NSRunLoop currentRunLoop] addTimer:self.commonRunTimer forMode:NSRunLoopCommonModes];
因为runLoop默认的运行模式是:NSDefaultRunLoopMode。在iOS系统下,为了提高界面的响应速度,在用于对屏幕进行操作时,会暂停一些运算,尤其是涉及到滚动视图这种需要流畅响应的视图。
用手拖动右侧滚动试图没有影响,因为它不会上下滚动。
所以我们显示地把这个定时器加到NSRunLoopCommonModes运行模式下,就会忽略界面操作的影响,可以不受界面操作的干扰,正常执行异步方法了。
最新文章
- Microsoft VS 2008 过期解决方法破解方法
- SQL注入的常用函数和语句
- PE的一些水 3-50
- gulp.spriteSmith使用
- Part 98 Anonymous methods in c#
- PHP面向对象的基本写法(区别于java)
- sed替换文件中的字符串
- 2015湖南省选集训DAY5——work(BZOJ4177)
- 开发Angular库的简单指导(译)
- HDU5410--01背包+完全背包
- 从零一起学Spring Boot之LayIM项目长成记(四) Spring Boot JPA 深入了解
- JavaWeb开发的一些问题
- cf757F Team Rocket Rises Again (dijkstra+支配树)
- linux系统编程:read,write与lseek的综合应用
- 在Android Studio中调用so中的方法
- 【docker】【Gitlab】gitlab中clone项目时,IP地址是一串数字(内网Gitlab的IP地址不正确)的问题解决
- js用img代替ajax js心跳 向服务器定时传送参数 主要计算用户在线时长
- python opencv3 静态图片检测人脸
- ajax 传递数组给后台.net MVC 控制器
- JavaScript 高级之面向对象
热门文章
- LeetCode 最大子序和
- js中小数精度问题
- Verilog学习笔记基本语法篇(二)·········运算符
- Linux下安装Oracle客户端
- Cocos2d-JS 实现将TiledMap中的每个 tile 变成物理精灵的方法
- sql server中的数据类型转换函数
- 九度oj 题目1250:矩阵变换
- ajax原生post请求
- Apple Pay强势来袭,开发者应做的事情(转)
- 【bzoj4408】[Fjoi 2016]神秘数 主席树