定义
- 运行循环
应用范畴
- 定时器, PerformSelector
- GCD
- 事件相应,手势识别,界面刷新
- 网络强求
- 自动释放池
RunLoop对象
iOS中有2套API 来访问和使用RunLoop
- Foundation :NSRunLoop
- Core Foundation : CFRunLoopRef
RunLoop对象 和线程的关系
- 每一个线程都有唯一的一个与之对应的runLoop对象
- RunLoop保存在一个全局的Dictionary 里 ,线程作为key ,RunLoop作value
- 线程刚创建时候并没有RunLoop对象,RunLoop会在第一次获取它时创建
- RunLoop会在线程结束时销毁
- 主线程的RunLoop已经自动获取,子线程默认没有开启RunLoop
RunLoop相关类
- Core Foundation中关于RunLoop的5个类
- CFRunLoopRef
- CFRunLoopModeRef
- CFRunLoopSourceRef
- CFRunLoopTimerRef
CFRunLoopObserverRef
image.png


CFRunLoopModeRef
- CFRunLoopModeRef 代表 RunLoop 的运行模式
- 一个RunLoop包含若干个Mode 每个Mode 又包含若干个 Source0/Source1/Timer/Observer
- RunLoop启动时只能选择其中一个Mode 作为 currentMode
-
如果需要切换mode 只能退出当前Loop 再重新选择一个mode进入
image.png

RunLoop状态

添加Observer监听 RunLoop的所有状态


RunLoop的应用
- 控制线程声明周期(线程保活)
- 解决NSTimer在滑动时停止工作的问题
- 监听应用卡顿
- 性能优化
解决NSTimer在滑动时停止工作的问题
static int count = 0 ;
NSTimer * timer = [NSTimer timerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"%d",++count);
}];
//NSRunLoopCommonModes 通用模式
//并不是一个真的模式 只是一个标记
//timer 在设置了Common标记的模式下都能运行
[[NSRunLoop currentRunLoop ]addTimer:timer forMode:NSRunLoopCommonModes];
网友评论