標籤:
什麼是RunLoop?
-RunLoop就是訊息迴圈,每一個線程內部都有一個訊息迴圈。 -只有主線程的訊息迴圈預設開啟,子線程的訊息迴圈預設不開啟。
RunLoop的目的 -保證程式不退出 。 -負責處理輸入事件。 -如果沒有事件發生,會讓程式進入休眠狀態 。
事件類型Input Sources (輸入源) & Timer Sources (定時源)
-輸入源可以是鍵盤滑鼠,NSPort, NSConnection 等對象,定時源是NSTimer 事件
添加訊息到迴圈中
-建立輸入源。(以NSTimer為例)
-指定該事件(源)在迴圈中啟動並執行模式,並加入迴圈。
[self performSelector:@selector(demo2) onThread:thread withObject:nil waitUntilDone:NO];[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
迴圈常用模式
NSDefaultRunLoopMode--預設模式
NSRunLoopCommonModes--普通模式
//1.NSTimer定時源 NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(demo) userInfo:nil repeats:YES]; //2.把定時源加入到當前線程的訊息迴圈中 /* 1.定時源 2.模式 NSDefaultRunLoopMode 觸摸介面->timer停止->手放開->timer運行 NSRunLoopCommonModes 觸摸介面不受影響 觸摸介面kCFRunLoopDefaultMode->UITrackingRunLoopMode->手放開->kCFRunLoopDefaultMode */ [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes]; //3.當訊息迴圈的模式和訊息的模式相匹配,訊息才能運行
總結
1.建立訊息
2.把訊息放入迴圈,並指定訊息啟動並執行模式
3.在與迴圈的模式比對的時候,訊息運行
子線程中的訊息迴圈
//子線程的訊息迴圈 NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(demo) object:nil]; [thread start]; //輸入源 /* 1.方法 2.線程 3.參數 4.是否等待方法的完成 */ //建立輸入源,加入到子線程的訊息迴圈 //只有主線程的訊息迴圈預設開啟,子線程的訊息迴圈預設不開啟。->手動開啟子線程的訊息迴圈 [self performSelector:@selector(talk) onThread:thread withObject:nil waitUntilDone:NO];
-(void)demo{ NSLog(@"demo is running");// NSLog(@"%@",[NSRunLoop currentRunLoop].currentMode); //手動開啟子線程的訊息迴圈 //1.run方法開了關不了OC [[NSRunLoop currentRunLoop] run]; //2.指定時間->不靠譜 不確定方法具體執行的時間長度等等因素// [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]]; //3.apple推薦(瞭解)// BOOL shouldKeepRunning = YES; // global// NSRunLoop *theRL = [NSRunLoop currentRunLoop];// while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]); NSLog(@"ok");
IOS - RunLoop訊息迴圈