Runloop 相关知识点。相当于while循环,不同点是runloop会睡眠,等待任务的唤醒。
- 一条线程对应一个runloop对象
- 主线程是系统方法
UIApplicationMain自动创建好的,并维护的 - 子线程的runloop需要自己创建和管理
RunLoop 相关类
CFRunLoopRef:代表 RunLoop 的对象
CFRunLoopModeRef:代表 RunLoop 的运行模式
CFRunLoopSourceRef:就是 RunLoop 模型图中提到的输入源 / 事件源
CFRunLoopTimerRef:就是 RunLoop 模型图中提到的定时源
CFRunLoopObserverRef:观察者,能够监听 RunLoop 的状态改变
关系为: model1 = {modelRef : [CFRunLoopSourceRef,CFRunLoopTimerRef,CFRunLoopObserverRef]}
model2 = {modelRef : [CFRunLoopSourceRef,CFRunLoopTimerRef,CFRunLoopObserverRef]}
runloop = [model1,model2];
runing(model1),或runing(model2),每次的运行模式只能是其中一种model1或model2。要切换model,只能等loop完成才可以。
NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
// 不操作UI时,runloop处于NSDefaultRunLoopMode模式
// 操作UI时,runloop处于UITrackingRunLoopMode模式
// 两种模式不能互相影响
dispatch_async(dispatch_get_global_queue(0, 0), ^{
weakSelf.timer = [NSTimer scheduledTimerWithTimeInterval:1.0
target:self
selector:@selector(repeat)
userInfo:nil
repeats:true];
[[NSRunLoop currentRunLoop] run];
});
// 在子线程的添加的runloop需要手动启动,退出runloop也需要手动停止。