什么是Runloop?

从字面上看就是运行循环,其实内部就是do-while循环,底层是GCD实现的,在这个循环内部不断处理各种事件(比如Source,Timer.Observer) 一个线程对应一个Runloop(线程是Key Runloop是value)主线程默认启动,子线程要手动启动(调用run) Runloop只能选择一个Mode启动,如果当前Mode中没有任何(set)Source和(Array)Timer,(Array)Observer,就会退出Runloop

你在开发中怎么使用Runloop?什么应用场景?

    开启常驻线程(让一个子线程不进入消亡状态,等待其他线程发来的消息,处理其他事件)比如在子线程开启一个定时器,在子线程中长期监控一些行为(监控用户的沙盒变化,监控网络状态),可以控制定时器在特定模式下进行,可以让某些事件(行为,任务)在特定模式下执行,可以添加Observer监听Runloop的状态(比如监听点击事件之前做一些处理)

自动释放池什么时候释放?

     在Runloop睡眠之前释放(KCFRunLoopBeforeWaiting)

定时器的多种实现:NSTimer是Runloop实现的可能不会准([NSTimer scheduledTimerWithTimeInterval:<#(NSTimeInterval)#> target:<#(nonnull id)#> selector:<#(nonnull SEL)#> userInfo:<#(nullable id)#> repeats:<#(BOOL)#>],

                                GCD的定时器,不受Runloop模式的影响,但是需要开启并且需要强引用

                                 @property (nonatomic,strong) dispatch_source_t time;

                                 dispatch_queue_t queue= dispatch_get_global_queue(0, 0);

                                 dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);

                                 dispatch_source_set_timer(self.timer, DISPATCH_TIME_NOW, NSEC_PER_SEC, 0);

                                 dispatch_source_set_event_handler(self.timer, ^{

    

                                });

                                 dispatch_resume(self.timer);

                                 取消只需置 self.timer = nil

挥毫泼墨,书写人生篇章
原文地址:https://www.cnblogs.com/Jusive/p/5248502.html