1、RunLoop
-
1)运行循环:
-
2)子线程运行循环:
-
3)响应者链条事件监听过程:
![RunLoop1]()
2、运行循环的使用
2.1 时钟调度
/*
- (void)addTimer:(NSTimer *)timer forMode:(NSString *)mode;
NSDefaultRunLoopMode: 时钟,网络。 发生用户交互的时候,时钟会被暂停
NSRunLoopCommonModes: 用户交互,响应级别高。 发生用户交互的时候,时钟仍然会触发,如果时钟触发方法非常耗时,
使用此方式时用户操作会造成非常严重的卡顿。
*/
-
以 NSRunLoopCommonModes 方式创建
// 调度时钟
self.timer = [NSTimer timerWithTimeInterval:1.0
target:self
selector:@selector(updateTimer)
userInfo:nil
repeats:YES];
// 将时钟以 NSRunLoopCommonModes 模式添加到运行循环
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
-
以 NSDefaultRunLoopMode 方式创建
// 调度时钟
/*
默认将时钟以 NSDefaultRunLoopMode 模式添加到运行循环
*/
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(updateTimer)
userInfo:nil
repeats:YES];
-
子线程运行循环
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// 在子线程开启时钟,由于子线程的运行循环没有启动,所以没法监听时钟事件
self.timer = [NSTimer timerWithTimeInterval:1.0
target:self
selector:@selector(updateTimer)
userInfo:nil
repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
// 启动子线程的运行循环,这句代码就是一个死循环!如果不停止运行循环,不会执行后续的任何代码
CFRunLoopRun();
// 停止子线程运行循环之前,不会执行添加到此处的任何代码
});
// 运行循环执行操作方法
- (void)updateTimer {
static int num = 0;
NSLog(@"%d %@", num++, [NSThread currentThread]);
// 满足条件后,停止当前的运行循环
if (num == 8) {
// 一旦停止了运行循环,后续代码能够执行,执行完毕后,线程被自动销毁
CFRunLoopStop(CFRunLoopGetCurrent());
}
}