CFRunLoop
2018-11-27 本文已影响8人
小行为
CFRunLoop 数据结构


CFRunLoopMode数据结构

name: NSDefaultRunLoopMode(对应mode名称)
集合结构:
source0: 手动唤醒线程
source1: 具备唤醒线程的能力
数组结构:
CFRunLoopTimer : 基于事件的定时器
CFRunTimeObservers: 观测时间点等
观测时间点
观测时间点
各个数据结构之前的关系

RunLoop的Mode

如何把一个timer添加到多个mode上 ???

事件循环的实现机制

RunLoop的核心

RunLoop与 NSTimer相关面试问题
如何把NSTimer同步添加到多个Mode上的??


RunLoop和多线程相关问题
static NSThread *thread = nil;
// 标记是否要继续事件循环
static BOOL runAlways = YES;
+ (NSThread *)threadForDispatch{
if (thread == nil) {
@synchronized(self) {
if (thread == nil) {
// 线程的创建
thread = [[NSThread alloc] initWithTarget:self selector:@selector(runRequest) object:nil];
[thread setName:@"com.imooc.thread"];
//启动
[thread start];
}
}
}
return thread;
}
+ (void)runRequest
{
// 创建一个Source
CFRunLoopSourceContext context = {0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
// 创建RunLoop,同时向RunLoop的DefaultMode下面添加Source
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
// 如果可以运行
while (runAlways) {
@autoreleasepool {
// 令当前RunLoop运行在DefaultMode下面
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e10, true);
}
}
// 某一时机 静态变量runAlways = NO时 可以保证跳出RunLoop,线程退出
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
CFRelease(source);
}