main函數(shù)為什么是一直運(yùn)行的?
RunLoop整個(gè)流程圖
#import "MCObject.h"
@implementation MCObject
static NSThread *thread = nil;
// 標(biāo)記是否要繼續(xù)事件循環(huán)
static BOOL runAlways = YES;
+ (NSThread *)threadForDispatch{
if (thread == nil) {
@synchronized(self) {
if (thread == nil) {
// 線程的創(chuàng)建
thread = [[NSThread alloc] initWithTarget:self selector:@selector(runRequest) object:nil];
[thread setName:@"com.imooc.thread"];
//啟動(dòng)
[thread start];
}
}
}
return thread;
}
+ (void)runRequest
{
// 創(chuàng)建一個(gè)Source
CFRunLoopSourceContext context = {0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
// 創(chuàng)建RunLoop旧烧,同時(shí)向RunLoop的DefaultMode下面添加Source
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
// 如果可以運(yùn)行
while (runAlways) {
@autoreleasepool {
// 令當(dāng)前RunLoop運(yùn)行在DefaultMode下面
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e10, true);
}
}
// 某一時(shí)機(jī) 靜態(tài)變量runAlways = NO時(shí) 可以保證跳出RunLoop,線程退出
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
CFRelease(source);
}
@end