- 子線程的消息循環是默認不開啟.
- 在子線程中使用
定時源
.即定時器
.需要我們手動開啟子線程的消息循環
. - 步驟 : 將
定時源
添加到當前線程
的消息循環.
1 - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event 2 { 3 [self performSelectorInBackground:@selector(timerDemo) withObject:nil]; 4 } 5 6 - (void)timerDemo 7 { 8 NSLog(@"begin"); 9 10 // 1.創建定時器 11 NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(fireDemo) userInfo:nil repeats:YES]; 12 13 // 2.把定時器添加到當前子線程的運行循環(子線程的運行循環默認不開啟) 14 [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode]; 15 16 // 3.手動開啟子線程的運行循環 (這個是主線程的運行循環和子線程的運行循環唯一的不同點) 17 // run : 一旦調用這個方法開啟子線程的運行循環,就不會停止 18 // 一旦開啟運行循環,相當於就開啟了死循環 19 [[NSRunLoop currentRunLoop] run]; 20 21 // runUntilDate : 讓子線程的運行循環,只執行指定的時間 22 // [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:3.0]]; 23 24 // 永遠不會執行,因為runUntilDate沒有打開, 25 NSLog(@"end"); 26 } 27 28 - (void)fireDemo 29 { 30 NSLog(@"hello"); 31 }
問題:子線程消息循環開啟后,后面的代碼不會執行,主線程怎么可以?
答:主線程的消息循環是默認開啟的,就是用來處理UI交互的。