Grand Central Dispatch (GCD) 是 Apple 開發(fā)的一個多核編程的解決方法。該方法在 Mac OS X 10.6 雪豹中首次推出,并隨后被引入到了 iOS4.0 中。GCD 是一個替代諸如 NSThread, NSOperationQueue, NSInvocationOperation 等技術(shù)的很高效和強大的技術(shù)。
GCD 和 block 的配合使用,可以方便地進行多線程編程。
讓我們來看一個編程場景。我們要在 iphone 上做一個下載網(wǎng)頁的功能,該功能非常簡單,就是在 iPhone 上放置一個按鈕,點擊該按鈕時,顯示一個轉(zhuǎn)動的圓圈,表示正在進行下載,下載完成之后,將內(nèi)容加載到界面上的一個文本控件中。
雖然功能簡單,但是我們必須把下載過程放到后臺線程中,否則會阻塞 UI 線程顯示。所以,如果不用 GCD, 我們需要寫如下 3 個方法:
someClick 方法是點擊按鈕后的代碼,可以看到我們用 NSInvocationOperation 建了一個后臺線程,并且放到 NSOperationQueue 中。后臺線程執(zhí)行 download 方法。download 方法處理下載網(wǎng)頁的邏輯。下載完成后用 performSelectorOnMainThread 執(zhí)行 download_completed 方法。download_completed 進行 clear up 的工作,并把下載的內(nèi)容顯示到文本控件中。這 3 個方法的代碼如下。可以看到,雖然 開始下載 -> 下載中 -> 下載完成 這 3 個步驟是整個功能的三步。但是它們卻被切分成了 3 塊。他們之間因為是 3 個方法,所以還需要傳遞數(shù)據(jù)參數(shù)。如果是復雜的應用,數(shù)據(jù)參數(shù)很可能就不象本例子中的 NSString 那么簡單了,另外,下載可能放到 Model 的類中來做,而界面的控制放到 View Controller 層來做,這使得本來就分開的代碼變得更加散落。代碼的可讀性大大降低。
| static NSOperationQueue * queue;- (IBAction)someClick:(id)sender {    self.indicator.hidden = NO;    [self.indicator startAnimating];    queue = [[NSOperationQueue alloc] init];    NSInvocationOperation * op = [[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(download) object:nil] autorelease];    [queue addOperation:op];}- (void)download {    NSURL * url = [NSURL URLWithString:@"http://www.youdao.com"];    NSError * error;    NSString * data = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];    if (data != nil) {        [self performSelectorOnMainThread:@selector(download_completed:) withObject:data waitUntilDone:NO];    } else {        NSLog(@"error when download:%@", error);        [queue release];    }}- (void) download_completed:(NSString *) data {    NSLog(@"call back");    [self.indicator stopAnimating];    self.indicator.hidden = YES;    self.content.text = data;    [queue release];} | 
如果使用 GCD,以上 3 個方法都可以放到一起,如下所示:
| // 原代碼塊一self.indicator.hidden = NO;[self.indicator startAnimating];dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // 原代碼塊二 NSURL * url = [NSURL URLWithString:@"http://www.youdao.com"]; NSError * error; NSString * data = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error]; if (data != nil) { // 原代碼塊三 dispatch_async(dispatch_get_main_queue(), ^{ [self.indicator stopAnimating]; self.indicator.hidden = YES; self.content.text = data; }); } else { NSLog(@"error when download:%@", error); }}); | 
首先我們可以看到,代碼變短了。因為少了原來 3 個方法的定義,也少了相互之間需要傳遞的變量的封裝。
另外,代碼變清楚了,雖然是異步的代碼,但是它們被 GCD 合理的整合在一起,邏輯非常清晰。如果應用上 MVC 模式,我們也可以將 View Controller 層的回調(diào)函數(shù)用 GCD 的方式傳遞給 Modal 層,這相比以前用 @selector 的方式,代碼的邏輯關(guān)系會更加清楚。
block 的定義有點象函數(shù)指針,差別是用 ^ 替代了函數(shù)指針的 * 號,如下所示:
|     // 申明變量    (void) (^loggerBlock)(void);    // 定義   loggerBlock = ^{          NSLog(@"Hello world");    };    // 調(diào)用    loggerBlock(); | 
但是大多數(shù)時候,我們通常使用內(nèi)聯(lián)的方式來定義 block,即將它的程序塊寫在調(diào)用的函數(shù)里面,例如這樣:
| dispatch_async(dispatch_get_global_queue(0, 0), ^{     // something}); | 
從上面大家可以看出,block 有如下特點:
程序塊可以在代碼中以內(nèi)聯(lián)的方式來定義。程序塊可以訪問在創(chuàng)建它的范圍內(nèi)的可用的變量。為了方便地使用 GCD,蘋果提供了一些方法方便我們將 block 放在主線程 或 后臺線程執(zhí)行,或者延后執(zhí)行。使用的例子如下:
| //  后臺執(zhí)行:dispatch_async(dispatch_get_global_queue(0, 0), ^{     // something});// 主線程執(zhí)行:dispatch_async(dispatch_get_main_queue(), ^{     // something});// 一次性執(zhí)行:static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{    // code to be executed once});// 延遲 2 秒執(zhí)行:double delayInSeconds = 2.0;dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);dispatch_after(popTime, dispatch_get_main_queue(), ^(void){    // code to be executed on the main queue after delay}); | 
dispatch_queue_t 也可以自己定義,如要要自定義 queue,可以用 dispatch_queue_create 方法,示例如下:
| dispatch_queue_t urls_queue = dispatch_queue_create("blog.devtang.com", NULL);dispatch_async(urls_queue, ^{     // your code});dispatch_release(urls_queue); | 
另外,GCD 還有一些高級用法,例如讓后臺 2 個線程并行執(zhí)行,然后等 2 個線程都結(jié)束后,再匯總執(zhí)行結(jié)果。這個可以用 dispatch_group, dispatch_group_async 和 dispatch_group_notify 來實現(xiàn),示例如下:
| dispatch_group_t group = dispatch_group_create();dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{     // 并行執(zhí)行的線程一});dispatch_group_async(group, dispatch_get_global_queue(0,0), ^{     // 并行執(zhí)行的線程二});dispatch_group_notify(group, dispatch_get_global_queue(0,0), ^{     // 匯總結(jié)果}); | 
默認情況下,在程序塊中訪問的外部變量是復制過去的,即寫操作不對原變量生效。但是你可以加上 __block 來讓其寫操作生效,示例代碼如下:
| __block int a = 0;void  (^foo)(void) = ^{     a = 1;}foo();// 這里,a 的值被修改為 1 | 
使用 block 的另一個用處是可以讓程序在后臺較長久的運行。在以前,當 app 被按 home 鍵退出后,app 僅有最多 5 秒鐘的時候做一些保存或清理資源的工作。但是應用可以調(diào)用 UIapplication 的beginBackgroundTaskWithExpirationHandler方法,讓 app 最多有 10 分鐘的時間在后臺長久運行。這個時間可以用來做清理本地緩存,發(fā)送統(tǒng)計數(shù)據(jù)等工作。
讓程序在后臺長久運行的示例代碼如下:
| // AppDelegate.h 文件@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;// AppDelegate.m 文件- (void)applicationDidEnterBackground:(UIApplication *)application{    [self beingBackgroundUpdateTask];    // 在這里加上你需要長久運行的代碼    [self endBackgroundUpdateTask];}- (void)beingBackgroundUpdateTask{    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{        [self endBackgroundUpdateTask];    }];}- (void)endBackgroundUpdateTask{    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];    self.backgroundUpdateTask = UIBackgroundTaskInvalid;} | 
總體來說,GCD 能夠極大地方便開發(fā)者進行多線程編程。大家應該盡量使用 GCD 來處理后臺線程和 UI 線程的交互。
例子代碼如下:
#import <UIKit/UIKit.h>@interface ViewController : UIViewController@property IBOutlet UIButton *downloadButton;@property IBOutlet UIActivityIndicatorView *indicator;@property IBOutlet UITextView *textView;@end
#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; self.indicator.hidden = YES; self.textView.hidden = YES;}- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning];}- (IBAction)startDownload:(id)sender { [self.indicator setHidden:NO]; self.downloadButton.hidden = YES; [self.indicator startAnimating]; //download的任務使用gcd后臺線程執(zhí)行,包括數(shù)據(jù)的下載并且完成后切換到主線程了刷新ui即可 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSURL *url = [NSURL URLWithString:@"https://www.youdao.com"]; NSError * error; NSString * data = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error]; if (data != nil) { dispatch_async(dispatch_get_main_queue(), ^{ [self.indicator stopAnimating]; self.indicator.hidden = YES; self.textView.hidden = NO; self.textView.backgroundColor = [UIColor redColor]; NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[data dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]; self.textView.attributedText = attributedString; self.downloadButton.hidden = YES; }); } else { NSLog(@"error when download:%@", error); } });}@end
Swift 3.0的寫法
import UIKitclass ViewController: UIViewController { @IBOutlet weak var button: UIButton! @IBOutlet weak var indicatorView: UIActivityIndicatorView! @IBOutlet weak var htmltextView: UITextView! override func viewDidLoad() { super.viewDidLoad() self.indicatorView.isHidden = true self.htmltextView.isHidden = true } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func buttonSelected() { startDownload() } func startDownload() { self.button.isHidden = true self.indicatorView.isHidden = false self.indicatorView.startAnimating() DispatchQueue.global().async { let myURLString = "https://www.youdao.com" guard let myURL = URL(string: myURLString) else { print("Error: /(myURLString) doesn't seem to be a valid URL") return } do { let myHTMLString = try? String(contentsOf: myURL, encoding: .utf8) print("HTML : /(myHTMLString)") if myHTMLString != nil { DispatchQueue.main.async { self.button.isHidden = true self.htmltextView.isHidden = false self.indicatorView.stopAnimating() self.indicatorView.isHidden = true let attributes = [ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, ] let attributedString = NSAttributedString(string: myHTMLString!, attributes: attributes) self.htmltextView.attributedText = attributedString } } } } }}
新聞熱點
疑難解答