蘋果官方文件
主執行緒 main Thread
ios中我們寫的程式碼是被Event來呼叫
主執行緒 有一個 run loop用於接受Events
主執行緒 用於處理介面接觸的Event
Event處理程式碼執行時候會阻塞主執行緒
三種實現執行緒的方法
-
//進入後臺程式 執行一個耗時的方法 [self performSelectorInBackground:@selector(backWork) withObject:nil]; //後臺執行的方法 -(void) backWork{ NCLog(@"background thread %@",[NSThread currentThread]); sleep(5); //回到主執行緒 [self performSelectorOnMainThread:@selector(mainWork) withObject:nil waitUntilDone:NO]; } -(void) mainWork{ NCLog(@"main thread %@",[NSThread currentThread]); [self.indicator stopAnimating]; }
-
NSBlockOperation
//定義 一個task
NSBlockOperation *op=[NSBlockOperation blockOperationWithBlock:^{
NCLog(@"NSBlockOperation xxx....");
sleep(5);
[self performSelectorOnMainThread:@selector(mainWork) withObject:nil waitUntilDone:NO];
}];
//把task 加入到執行佇列
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperation:op];
- GCD 大中樞 相對NSOperation是更底層的框架.
用了block程式碼更加簡潔
“`
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NCLog(@”dispatch_async xxx….”);
[self.indicator startAnimating];
sleep(5); dispatch_async(dispatch_get_main_queue(), ^{
[self mainWork];
[self.indicator stopAnimating];
});
});
“`