runLoop創(chuàng)建一個(gè)常駐線程,多次用到子線程去處理事件,避免頻繁的創(chuàng)建,銷(xiāo)毀線程,每條線程都有一個(gè)RunLoop,他只有能獲取到RunLoop.主線程也是通過(guò)創(chuàng)建(main函數(shù)中)才有的RunLoop
- (void)viewDidLoad {
[super viewDidLoad];
[self threadTest];
}
- (void)threadTest{
NSThread *subThread = [[NSThread alloc] initWithTarget:self selector:@selector(subThreadEntryPoint) object:nil];
[subThread setName:@"TestThread"];
[subThread start];
self.subThread = subThread;
}
//子線程啟動(dòng)后,啟動(dòng)runloop
- (void)subThreadEntryPoint{
@autoreleasepool {
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
//如果注釋了下面這一行莫杈,子線程中的任務(wù)并不能正常執(zhí)行
//1.開(kāi)啟RunLoop死循環(huán)
[runLoop addPort:[NSMachPort port] forMode:NSRunLoopCommonModes];
//2.當(dāng)前RunLoop,并不是創(chuàng)建新的RunLoop,RunLoop是懶加載的過(guò)程,只有第一次是創(chuàng)建,雖然是死循環(huán),但是可以執(zhí)行該線程外(在此子線程上)的消息
[[NSRunLoop currentRunLoop] run];
//3.通過(guò)控制_finished值來(lái)中指RunLoop,或者更粗暴的終止線程[NSThread exit];
while(!_finished) {
[[NSRunLoop currentRunLoop]runUntilDate:[NSDatedateWithTimeIntervalSinceNow:0.0001]];
}
NSLog(@"啟動(dòng)RunLoop前--%@",runLoop.currentMode);
[runLoop run];
}
//子線程任務(wù)
- (void)subThreadOpetion{
NSLog(@"啟動(dòng)RunLoop后--%@",[NSRunLoop currentRunLoop].currentMode);
NSLog(@"%@----子線程任務(wù)開(kāi)始",[NSThread currentThread]);
[NSThread sleepForTimeInterval:3.0];//模擬事件}
NSLog(@"%@----子線程任務(wù)結(jié)束",[NSThread currentThread]);
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[self performSelector:@selector(subThreadOpetion) onThread:self.subThread
withObject:nil waitUntilDone:NO];
}
}