一、作用
1.使程序一直運行并接收用戶的輸入
2.決定程序在何時處理哪些事件
3.節(jié)省CPU時間(當程序啟動后,什么都沒有執(zhí)行的話,就不用讓CPU來消耗資源來執(zhí)行,直接進入睡眠狀態(tài))

runloop.png

runloop示意圖.png
二、模擬RunLoop的實現(xiàn)
void callFunc(int type) {
NSLog(@"正在執(zhí)行%d", type);
}
int main(int argc, const char * argv[]) {
@autoreleasepool{
int result = 0;
while (YES)
{
printf("請輸入選擇項,0表示退出:");
scanf("%d", &result);
if (result ==0) {
printf("88\n");
break;
} else {
callFunc(result);
}
}
}
return 0;
}
三、定時器和RunLoop
- (void)viewDidLoad {
[superviewDidLoad];
NSTimer*timer =[NSTimertimerWithTimeInterval:1.0target:selfselector:@selector(fire) userInfo:nil repeats:YES];
//添加到運行循環(huán)
//NSDefaultRunLoopMode : 默認模式,表示應用程序空閑,絕大多數(shù)的事件響應都是在這種模式:定時器
//UITrackingRunLoopMode : 滾動模式, 只有滾動模式下才會觸發(fā)定時器回調(diào)。
//NSRunLoopCommonModes : 默認包含1,2兩種模式
[[NSRunLoopcurrentRunLoop] addTimer:timer forMode: NSRunLoopCommonModes];
}
- (void)fire {
// 模擬睡眠
//在iOS9.0之前,線程休眠的時候,runLoop 不響應任何事件,開發(fā)中不建議使用。
// [NSThread sleepForTimeInterval:1.0];
static int num = 0;
/// 耗時操作
for (int i =0; i < 1000 * 1000; ++i) {
[NSString stringWithFormat:@"hello - %d", i];
}
NSLog(@"%d",num++);
}
##運行測試,會發(fā)現(xiàn)卡頓非常嚴重。
將時鐘添加到其他線程工作
- (void)viewDidLoad {
[superviewDidLoad];
NSThread *thread = [[NSThread alloc]initWithTarget:self selector:@selector(startTimer) object:nil];
[thread start];
}
- (void)startTimer {
NSLog(@"startTimer =%@",[NSThreadcurrentThread]);
NSTimer*timer = [NSTimertimerWithTimeInterval:1.0target:selfselector:@selector(fire) userInfo:nil repeats:YES];
//添加到運行循環(huán)
//NSDefaultRunLoopMode : 默認模式,表示應用程序空閑,絕大多數(shù)的事件響應都是在這種模式:定時器
//UITrackingRunLoopMode : 滾動模式, 只有滾動模式下才會觸發(fā)定時器回調(diào)。
//NSRunLoopCommonModes : 默認包含1,2兩種模式
//在實際開發(fā)中,不建議將定時器的運行循環(huán)模式設置為NSRunLoopCommonModes,在有耗時操作的時候會影響流暢度。
[[NSRunLoopcurrentRunLoop] addTimer:timer forMode: NSRunLoopCommonModes];
//runLoop最主要的作用:監(jiān)聽事件
//每一個線程都會有一個runLoop,默認情況下,只有主線程的 runLoop 是開啟的,子線程的
runLoop 是不開啟。
//啟動當前線程的runLoop -- 是一個死循環(huán)
//使用下面方法啟動,沒辦法在某一條件成立后手動停止runLoop,只能由系統(tǒng)停止。
// [[NSRunLoop currentRunLoop] run];
CFRunLoopRun();
NSLog(@"come here");
}
- (void)fire {
//模擬睡眠
//在iOS9.0之前,線程休眠的時候,runLoop 不響應任何事件,開發(fā)中不建議使用。
// [NSThread sleepForTimeInterval:1.0];
static int num = 0;
/// 耗時操作
for (int i =0; i < 1000 * 1000; ++i) {
[NSString stringWithFormat:@"hello - %d", i];
}
NSLog(@"%d---%@", num++,[NSThread currentThread]);
if (num == 2) {
NSLog(@"停止RunLoop");
// 停止RunLoop
CFRunLoopStop(CFRunLoopGetCurrent());
}
}
注意:主線程的運行循環(huán)是默認啟動的,但是子線程的運行循環(huán)是默認不工作的。