目錄
1. RunLoop簡介
2. RunLoop的相關(guān)類
3. RunLoop的應(yīng)用
1. 什么是RunLoop
** RunLoop** 中文譯為 運行循環(huán),其實內(nèi)部是一個 do - while 循環(huán),在這個循環(huán)中不斷地處理各種任務(wù)。一個線程對應(yīng)一個 RunLoop,主線程 RunLoop 默認(rèn)自動啟動,子線程RunLoop需要手動啟動(調(diào)用RunLoop的run方法)。
RunLoop 的代碼原理可簡單地理解為:
int main(int argc, char * argv[])
{
BOOL running = YES; // 程序開始
do{
// 執(zhí)行各種任務(wù)
} while(running);
return 0;
}
iOS中的程序入口 main 代碼如下:
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
iOS 中的程序入口 main 中,UIApplicationMain 函數(shù)內(nèi)部就啟動了一個RunLoop,所以 UIApplicationMain 就沒有返回,保持了程序的運行。這個默認(rèn)啟動的 RunLoop 是和 主線程 關(guān)聯(lián)的。
iOS 中有兩套API可以訪問 RunLoop:
- Core Foundation框架,基于C語言,CFRunLoopRef
- Foundation框架,基于Objective-C語言,NSRunLoop
CFRunLoopRef 和 NSRunLoop 都代表 RunLoop 對象,NSRunLoop 是對 CFRunLoopRef 的一層 OC 封裝。
RunLoop 與線程的關(guān)系:
- 每一個線程都有唯一的與之對應(yīng)的 RunLoop 對象。
- 主線程的 RunLoop 自動創(chuàng)建, 子線程的 RunLoop 需手動創(chuàng)建
- RunLoop 采用延遲加載,在第一次獲取時自動創(chuàng)建,在線程結(jié)束時銷毀。(調(diào)用[NSRunLoop currentRunLoop];就自動創(chuàng)建了 RunLoop 對象)。
2.RunLoop的相關(guān)類
Core Foundation有5個關(guān)于 RunLoop 的相關(guān)類
1. CFRunLoopRef
2. CFRunLoopModeRef
3. CFRunLoopSourceRef
4. CFRunLoopTimerRef
5. CFRunLoopObserverRef
2.1 CFRunLoopModeRef
CFRunLoopModeRef 代表 RunLoop 的 模式(Mode)。
- RunLoop 啟動時需要設(shè)置運行模式,RunLoop 的 模式 有五種不同類型可以選擇。
(1)NSDefaultRunLoopMode(kCFRunLoopDefaultMode):RunLoop 的默認(rèn) Mode,通常主線程在這個 Mode 下運行。
(2)UITrackingRunLoopMode:界面追蹤 Mode,用于 UIScrollView 追蹤,觸摸滑動,保證界面動畫不受其他Mode影響
(3)UIInitializationRunLoopMode:在剛啟動APP時進(jìn)入的第一個 Mode,啟動完成后就不再使用。(這個模式主要是蘋果在用,開發(fā)者用不到)
(4)GSEventReceiveRunLoopMode:接受系統(tǒng)事件的內(nèi)部 Mode(繪圖事件),通常開發(fā)者用不到。
(5)NSRunLoopCommonMode(kCFRunLoopCommonModes):這是一個占位 Mode,不是一個真正的 Mode。一個模式可以被標(biāo)記為 NSRunLoopCommonMode。默認(rèn)情況下,NSDefaultRunLoopMode 和 UITrackingRunLoopMode 被標(biāo)記為 NSRunLoopCommonMode,RunLoop 在這個模式下運行,則表示 RunLoop 可以同時執(zhí)行在 NSDefaultRunLoopMode 和 UITrackingRunLoopMode 兩個模式下。
- 一個 RunLoop 對象可以包含很多個模式,每個模式中可以包含多個Source、Observer、Timer,可以監(jiān)聽多個對象。
- RunLoop 只能選擇其中一種模式運行,這個Mode(模式)被稱作 CurrentMode。
- 如果需要切換 Mode,只能退出 RunLoop,再重新指定一個 Mode 進(jìn)入,這是為了分割不同 Mode 中的 Source,Timer 和 Observer,使他們互不影響。
- 一個如果 RunLoop 當(dāng)前 模式 沒有任何 Source、 Observer、 Timer,則 RunLoop 直接退出。
2.2 CFRunLoopTimerRef
CFRunLoopTimerRef 是基于時間的觸發(fā)器,一般說的就是NSTimer。
NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; // 該定時器,在正常模式下工作,在滾動事件(如UIScrollView滾動)時,不工作。
NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; // 在這種情況下,定時器可以同時工作在默認(rèn)狀態(tài)和滾動狀態(tài)。
2.3 CFRunLoopSourceRef
CFRunLoopSourceRef 譯為 事件源 或者 輸入源,主要包括:觸摸事件、點擊和performSelectorOnThread事件。
事件源 按照官方文檔可分為:
- Port-Based Sources:內(nèi)核發(fā)出的事件
- Custom Input Sources:自定義輸入源
- Cocoa Perform Selector Sources:performSelector事件源
按照函數(shù)調(diào)用棧可分為:
- Source0:非基于Port的事件源
- Source1:基于Port的事件源,通過內(nèi)核和其他線程通信,接收、分發(fā)系統(tǒng)事件
一旦發(fā)生 觸摸、點擊 或者 PerformSelectorOnThread事件,RunLoop就會處理這些事件。
2.4 CFRunLoopObServerRef
CFRunLoopObserverRef 是監(jiān)聽RunLoop 狀態(tài)改變的觀察者。它可以監(jiān)聽以下幾個時間點:
typedef CFOPTIONS(CFOptionFlags,CFRunLoopActivity)
{
kCFRunLoopEntry = (1UL << 0), // 即將進(jìn)入 RunLoop
kCFRunLoopBeforeTimers = (1UL << 1), // 即將處理 Timer
kCFRunLoopBeforeSources = (1UL << 2), // 即將處理 Source
kCFRunLoopBeforeWaiting = (1UL << 5), // 即將進(jìn)入 休眠
kCFRunLoopAfterWaiting = (1UL << 6), // 剛從休眠中喚醒
kCFRunLoopExit = (1UL << 7), // 即將退出 RunLoop
};
CFRunLoopObserverRef 是由C語言實現(xiàn)的,示例代碼:
// 創(chuàng)建Observer
CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(CFAllocatorGetDefault(), kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity)
{
NSLog(@"----監(jiān)聽RunLoop狀態(tài)改變,%lu",activity);
});
// 添加觀察者監(jiān)聽RunLoop狀態(tài)
CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopDefaultMode);
// 釋放Observer
CFRelease(Observer);
2.5 RunLoop的處理邏輯
3. RunLoop的應(yīng)用
RunLoop 的基本作用:
1、保持程序的運行
2、處理APP中的各種事件,如:觸摸事件、定時器事件、selector事件
3、節(jié)省CPU資源,提高程序性能(無任務(wù)時休息,有任務(wù)時工作)
在開發(fā)中的應(yīng)用:
- NSTimer
- PerformSelector調(diào)用
- 線程常駐
3.1 NSTimer的使用
NSTimer 定時器需要添加到 RunLoop 中才能啟動。
// 創(chuàng)建NSTimer對象
NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
// 將NSTImer對象添加到NSRunLoop中
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
3.2 PerformSelector 特定模式下執(zhí)行
在 RunLoop 的特定模式下執(zhí)行某個方法。
[self performSelector:@selector(run) withObject:nil afterDelay:0 inModes:@[NSDefaultRunLoopMode]];
3.3 線程常駐
RunLoop 實現(xiàn)常駐線程,需要在線程中添加 RunLoop,并且在 RunLoop 中添加 Source 或者 Timer 。(添加 Observer RunLoop依舊會退出,因為 Observer 是被動觀察)
示例代碼如下:
// 子線程RunLoop 添加 NSPort 保持 RunLoop 持續(xù)執(zhí)行
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically
// 創(chuàng)建線程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(execute) object:nil];
self.thread = thread;
// 開啟線程
[thread start];
}
- (void)execute
{
@autoreleasepool {
// 線程中開啟RunLoop
// 在RunLoop中添加Port,使RunLoop不退出
[[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSRunLoopCommonModes];
// 啟動RunLoop
[[NSRunLoop currentRunLoop] run];
}
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 在子線程中響應(yīng)點擊事件
[self performSelector:@selector(test) onThread:self.thread withObject:nil waitUntilDone:NO];
}
- (void)test
{
NSLog(@"test----");
}
// 子線程RunLoop 添加 NSTimer定時執(zhí)行某項任務(wù) 保持 RunLoop 持續(xù)執(zhí)行
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically
// 創(chuàng)建線程
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(execute) object:nil];
self.thread = thread;
// 開啟線程
[thread start];
}
- (void)execute
{
@autoreleasepool {
// 創(chuàng)建NSTimer對象
NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(test) userInfo:nil repeats:YES];
// 線程中開啟RunLoop
// 在RunLoop中添加NSTimer,使RunLoop持續(xù)運行
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
// 啟動RunLoop
[[NSRunLoop currentRunLoop] run];
}
}
- (void)test
{
NSLog(@"test----");
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
// 在子線程中響應(yīng)點擊事件
[self performSelector:@selector(test2) onThread:self.thread withObject:nil waitUntilDone:NO];
}
- (void)test2
{
NSLog(@"*****test2*****");
}
3.4 RunLoop與自動釋放池
在ARC模式下,系統(tǒng)自動將OC對象放入自動釋放池管理,在自動釋放池釋放時,在自動釋放池中的對象統(tǒng)一執(zhí)行一次 release 方法。
自動釋放池在 RunLoop 休眠之前釋放。
在子線程中使用 RunLoop 時,需要將 RunLoop 相關(guān)代碼放入自動釋放池中。