這一節用兩個具體場景把 GCD 最常用的模式跑一遍:一是認識主隊列的特性,二是「子線程下載圖片 → 主線程更新界面」這個幾乎每個 App 都會用到的標準套路。
主隊列是與主線程關聯的隊列,也是 GCD 提供的一種特殊隊列。加入主隊列的任務都會在主線程執行。關鍵點:往主隊列加任務,無論同步還是異步,都不會建立新線程。
#import "ViewController.h"
@interface ViewController () {
UIImageView *_view;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// dispatch_get_main_queue() 取得主隊列
// 開一條子線程執行 test
[self performSelectorInBackground:@selector(test) withObject:nil];
_view = [[UIImageView alloc] init];
_view.frame = CGRectMake(0, 0, self.view.bounds.size.width, 300);
[self.view addSubview:_view];
}
- (void)test {
dispatch_queue_t queue = dispatch_queue_create("Concurrent Queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
NSLog(@"222 curThread = %@", [NSThread currentThread]);
});
dispatch_sync(queue, ^{
NSLog(@"333 cureThread = %@", [NSThread currentThread]);
});
}
點擊螢幕下載一張網絡圖片並顯示。網絡請求必須離開主線程,UI 操作必須回到主線程:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 1. 取全域並發隊列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// 2. 異步下載圖片
dispatch_async(queue, ^{
NSLog(@"1111 : curThread = %@", [NSThread currentThread]);
NSURL *url = [NSURL URLWithString:@"https://h.hiphotos.baidu.com/image/pic/item/35a85edf8db1cb13966db40fde54564e92584ba2.jpg"];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
// 3. 回到主線程設置圖片
// 好處:在主線程中可直接使用子線程取得的資源,直觀方便
dispatch_async(dispatch_get_main_queue(), ^{
_view.image = image;
});
});
}
實務上很少直接寫 dataWithContentsOfURL:(它是同步的,且無法取消、無法追蹤進度),通常會封裝成這樣的形式:
- (void)test11 {
dispatch_queue_t queue = dispatch_queue_create("Concurrent Queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
// 耗時操作(網絡、磁盤、計算)
dispatch_async(dispatch_get_main_queue(), ^{
// 回到主線程操作 UI
});
});
}
三點實務建議:一是用 NSURLSession 取代 dataWithContentsOfURL:,它天生異步且可配置超時、快取與重試;二是切回主線程時留意 self 的生命週期,必要時用 weak 修飾避免循環引用;三是若只是為了更新圖片,直接用 NSURLSession 的 dataTask 回調(本身已在主隊列)或 SDWebImage 這類成熟庫,不必自己拼線程。