原文地址:http://www.it165.net/pro/html/201209/3721.html
在Objective-C中,有三种多线程机制,一种是NSThread,一种是NSOperation,一种是GCD。
前面两篇文章我们讲述了NSThread和NSOperation。这里我们来说明一下GCD的方法。在前文中,我们写过关于GCD的文章。
GCD多线程编程方法主要基于下面几个属性和方法:
dispatch_queue_t,dispatch_get_global_queue,dispatch_async.
在定义中可以给定多个dispatch_async方法,这些方法有顺序性。比如从网络下载图片这个场景,程序第一个dispatch_async方法为下载图片下来,如果失败则返回错误。第二个dispatch_async方法则将这个图片在主线程中显示加载,如果失败则显示默认图片等。
代码演示如下:
01.
- (
void
) viewDidAppear:(BOOL)paramAnimated{
02.
dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
0
);
03.
dispatch_async(concurrentQueue, ^{
04.
__block UIImage *image = nil;
05.
dispatch_sync(concurrentQueue, ^{
06.
/* Download the image here */
07.
/* iPad's image from Apple's website. Wrap it into two lines as the URL is too long to fit into one line */
08.
NSString *urlAsString = @
"http://images.apple.com/mobileme/features"
\
"/images/ipad_findyouripad_20100518.jpg"
;
09.
NSURL *url = [NSURL URLWithString:urlAsString];
10.
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
11.
NSError *downloadError = nil;
12.
NSData *imageData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&downloadError];
13.
if
(downloadError == nil && imageData != nil){
14.
image = [UIImage imageWithData:imageData];
/* We have the image. We can use it now */
15.
}
16.
else
if
(downloadError != nil){
17.
NSLog(@
"Error happened = %@"
, downloadError);
18.
}
19.
else
20.
{
21.
NSLog(@
"No data could get downloaded from the URL."
);
22.
}
23.
});
24.
25.
dispatch_sync(dispatch_get_main_queue(), ^{
26.
/* Show the image to the user here on the main queue*/
27.
if
(image != nil){
28.
/* Create the image view here */
29.
UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
30.
/* Set the image */
31.
[imageView setImage:image];
32.
/* Make sure the image is not scaled incorrectly */
33.
[imageView setContentMode:UIViewContentModeScaleAspectFit];
34.
/* Add the image to this view controller's view */
35.
[self.view addSubview:imageView];
36.
}
else
{
37.
NSLog(@
"Image isn't downloaded. Nothing to display."
);
38.
}
39.
});
40.
});
41.
}