RunLoop

作者: 开发界小学生 | 来源:发表于2018-08-13 17:59 被阅读0次

什么是RunLoop

在程序运行中不断的循环做一些事情
应用范畴:定时器,PerfromSelector, GCD Async Main Queue,事件响应,手势识别,界面刷新,网络请求 AutoreleasePool

Runloop跟线程的关系

runloop与线程是一一对应的,一个runloop对应一个核心的线程,为什么说是核心的,是因为runloop是可以嵌套的,但是核心的只能有一个,他们的关系保存在一个全局的字典里。
runloop是来管理线程的,当线程的runloop被开启后,线程会在执行完任务后进入休眠状态,有了任务就会被唤醒去执行任务。
runloop在第一次获取时被创建,在线程结束时被销毁。
对于主线程来说,runloop在程序一启动就默认创建好了。
对于子线程来说,runloop是懒加载的,只有当我们使用的时候才会创建,所以在子线程用定时器要注意:确保子线程的runloop被创建,不然定时器不会回调。

Runloop的运行逻辑

EAA9D19B-8B8C-4395-8128-5C3C7937AF0F.png

Runloop解决定时器问题

static int a = 0;
    NSTimer * time = [NSTimer timerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        NSLog(@"%ld",a++);
    }];
    [[NSRunLoop currentRunLoop] addTimer:time forMode: UITrackingRunLoopMode];

控制线程生命周期

当线程runloop开启没有source0 source1 nstimer的时候。runloop会退出

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    BBThread * thread = [[BBThread alloc] initWithTarget:self selector:@selector(run) object:nil];
    [thread start];
}
- (void)run{
    NSLog(@"%@",[NSThread currentThread]);
    [[NSRunLoop currentRunLoop] addPort:[NSPort new] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];   
}

相关文章

网友评论

      本文标题:RunLoop

      本文链接:https://www.haomeiwen.com/subject/legubftx.html