NSRunloop和NSThread的情感纠葛

一直觉得runloop这东西很神奇、很飘渺,现在还是觉得这玩意很飘渺 -_-.

前两天特地花了点时间看了下官方的文档,把我理解的和觉得重要的跟大家分享下,欢迎批评指正。

线程实现的几种方式:
1. Operation Objects   // NSOperation及相关子类
2. G C D                           // dispatch_async等相关函数  擦,这也会被和谐-_-
3. Idle-time notifications  //  NSNotificationQueue,低优先级
3. Asynchronous functions  // 异步函数
4. Timers                      // NSTimer
5. Separate processes  // 没用过

线程创建的成本:
kernel data structures  约1KB
Stack space             512KB(secondary threads) 
                                   1MB(iOS main thread)
Creation time           约90 microseconds

Run Loop和线程的关系:
1. 主线程的run loop默认是启动的,用于接收各种输入sources
2. 对第二线程来说,run loop默认是没有启动的,如果你需要更多的线程交互则可以手动配置和启动,如果线程执行一个长时间已确定的任务则不需要。

Run Loop什么情况下使用:
a. 使用ports 或 input sources 和其他线程通信   // 不了解
b. 在线程中使用timers                                             // 如果不启动run loop,timer的事件是不会响应的 
c. 在Cocoa 应用中使用performSelector...方法   // 应该是performSelector...这种方法会启动一个线程并启动run loop吧
d. 让线程执行一个周期性的任务                            // 如果不启动run loop, 线程跑完就可能被系统释放了

注:timer的创建和释放必须在同一线程中。(官方原文: as a result, you should always call the invalidate method from the same thread on which the timer was installed.)
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];  此方法会retain timer对象的引用计数。

官方文档: NSRunloop 官方文档

原文地址:https://www.cnblogs.com/iOSJason/p/4089473.html