这里强调一点:在主线程中以+scheduledTimerWithTimeInterval...的方式触发的timer 默认是运行在 NSDefaultRunLoopMode 模式下的,当滑动页面上的列表时,进入了 UITrackingRunLoopMode 模式,这时候 timer 就会停止可以修改 timer 的运行模式为 NSRunLoopCommonModes,这样定时器就可以一直运行了
以下是我的笔记补充:
在子线程中通过
scheduledTimerWithTimeInterval:...方法来构建NSTimer
方法内部已经创建
NSTimer 对象,并加入到
RunLoop
中,运行模式为NSDefaultRunLoopMode
由于 Mode
有 timer
对象,所以 RunLoop
就开始监听定时器事件了,从而开始进入运行循环
这个方法仅仅是创建
RunLoop
对象,并不会主动启动
RunLoop,需要再调用
run方法来启动
如果在主线程中通过 scheduledTimerWithTimeInterval:...方法来构建 NSTimer,就不需要主动启动 RunLoop 对象,因为主线程的 RunLoop 对象在程序运行起来就已经被启动了 //userInfo参数:用来给NSTimer的userInfo 属性赋值,userInfo 是只读的,只能在构建 NSTimer 对象时赋值
[NSTimer scheduledTimerWithTimeInterval:1.0 target:selfselector:@selector(run:) userInfo:@"ya 了 个 hoo"repeats:YES];
// scheduledTimer...方法创建出来
NSTimer
虽然已经指定了默认模式,但是【允许你修改模式】
[[NSRunLoop currentRunLoop] addTimer:timerforMode:NSRunLoopCommonModes];
//
【仅在子线程】需要手动启动
RunLoop
对象,进入运行循环[[NSRunLoop currentRunLoop] run];
本文详细解析了如何在主线程及子线程中使用NSTimer,并介绍了如何设置定时器的运行模式以确保其正常工作。此外,还探讨了RunLoop的工作原理及其与定时器之间的关系。
2002

被折叠的 条评论
为什么被折叠?



