GCD 真正的威力,要等到你把非 UI 的運算丟到主佇列以外的佇列上才看得見。UI 相關的操作必須留在主佇列,其餘的網路下載、檔案讀寫、大量資料處理,都應該異步執行以免卡住畫面。
dispatch_async:向分派佇列異步提交一個 Block。
dispatch_async(concurrentQueue, ^{ /* ... */ });
dispatch_async_f:向分派佇列異步提交一個 C 函式與上下文指標。
dispatch_async_f(concurrentQueue, NULL, printFrom1To1000);
- (void) viewDidAppear:(BOOL)paramAnimated{
// 建立全域並行佇列
dispatch_queue_t concurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{
__block UIImage *image = nil;
dispatch_sync(concurrentQueue, ^{
/* 下載圖片 */
NSString *urlAsString = @"https://up.2cto.com/2013/0519/20130519101223949.jpg";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSError *downloadError = nil;
NSData *imageData = [NSURLConnection
sendSynchronousRequest:urlRequest
returningResponse:nil
error:&downloadError];
if (downloadError == nil && imageData != nil){
// 將 NSData 轉為圖片
image = [UIImage imageWithData:imageData];
}
else if (downloadError != nil){
NSLog(@"Error happened = %@", downloadError);
}else{
NSLog(@"No data could get downloaded from the URL.");
}
});
// 回到主執行緒更新 UI
dispatch_sync(dispatch_get_main_queue(), ^{
if (image != nil){
UIImageView *imageView = [[UIImageView alloc]
initWithFrame:self.view.bounds];
[imageView setImage:image];
[imageView setContentMode:UIViewContentModeScaleAspectFit];
[self.view addSubview:imageView];
} else {
NSLog(@"Image isn't downloaded. Nothing to display.");
}
});
});
}
這個範例的重點是「分工」:下載在背景佇列、UI 更新切回主佇列。這樣的結構可以推廣到任何耗時任務。
@synthesize myLabel;
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_queue_t concurrentQueue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
/*
若磁碟上還沒有這份隨機數檔案,就先產生並寫入
*/
dispatch_async(concurrentQueue, ^{
NSUInteger numberOfValuesRequired = 10000;
if ([self hasFileAlreadyBeenCreated] == NO){
dispatch_sync(concurrentQueue, ^{
NSMutableArray *arrayOfRandomNumbers =
[[NSMutableArray alloc] initWithCapacity:numberOfValuesRequired];
NSUInteger counter = 0;
for (counter = 0; counter < numberOfValuesRequired; counter++){
unsigned int randomNumber = arc4random() % ((unsigned int)RAND_MAX + 1);
[arrayOfRandomNumbers addObject:
[NSNumber numberWithUnsignedInt:randomNumber]];
}
[arrayOfRandomNumbers writeToFile:[self fileLocation] atomically:YES];
});
}
// 讀回檔案並升序排序
__block NSMutableArray *randomNumbers = nil;
dispatch_sync(concurrentQueue, ^{
if ([self hasFileAlreadyBeenCreated]){
randomNumbers = [[NSMutableArray alloc]
initWithContentsOfFile:[self fileLocation]];
[randomNumbers sortUsingComparator:^NSComparisonResult(id obj1, id obj2)
{
NSNumber *number1 = (NSNumber *)obj1;
NSNumber *number2 = (NSNumber *)obj2;
return [number1 compare:number2];
}];
}
});
// 回到主執行緒刷新畫面
dispatch_async(dispatch_get_main_queue(), ^{
if ([randomNumbers count] > 0){
CGRect labelFrame = CGRectMake(0.0f, 0.0f, 300.0f, 200.0f);
self.myLabel = [[UILabel alloc] initWithFrame:labelFrame];
self.myLabel.numberOfLines = 10;
self.myLabel.text = [[NSString alloc] initWithFormat:
@"RandomNumbers is %@", randomNumbers];
self.myLabel.font = [UIFont boldSystemFontOfSize:14.0f];
self.myLabel.center = self.view.center;
[self.view addSubview:self.myLabel];
}
});
});
}
// 取得檔案路徑
-(NSString *)fileLocation{
/*
NSDocumentDirectory:文件目錄
NSUserDomainMask:使用者主目錄
*/
NSArray *folders = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
if ([folders count] == 0){ return nil; }
NSString *documentsFolder = [folders objectAtIndex:0];
return [documentsFolder stringByAppendingPathComponent:@"list.txt"];
}
// 判斷檔案是否已存在
- (BOOL) hasFileAlreadyBeenCreated{
NSFileManager *fileManager = [[NSFileManager alloc] init];
return [fileManager fileExistsAtPath:[self fileLocation]];
}
__block。補充一點:範例中的 NSURLConnection sendSynchronousRequest: 僅為教學示意,真實專案請改用 NSURLSession 的異步 API,並把回呼切回主佇列處理 UI。