什么是GCD?
不用GCD前虽然功能简单,但是我们必须把下载过程放到后台线程中,否则会阻塞UI线程显示。所以,如果不用GCD,我们需要写如下3个方法:
* download方法处理下载网页的逻辑。下载完成后用performSelectorOnMainThread执行download_completed方法。
* download_completed 进行clearup的工作,并把下载的内容显示到文本控件中。
-(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 = [NSURLURLWithString:@"http://blog.iosxcode4.com"];
NSError * error;
NSString
* data = [NSString stringWithContentsOfURL:urlencoding: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];
}
// 原代码块一
self.indicator.hidden = NO;
[self.indicator startAnimating];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{
// 原代码块二
NSURL * url = [NSURLURLWithString:@"http://blog.iosxcode4.com"];
NSError * error;
NSString * data = [NSString stringWithContentsOfURL:urlencoding: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);
}
});
另 外,代码变清楚了,虽然是异步的代码,但是它们被GCD合理的整合在一起,逻辑非常清晰。如果应用上MVC模式,我们也可以将 ViewController层的回调函数用GCD的方式传递给Modal层,这相比以前用@selector的方式,代码的逻辑关系会更加清楚。
//申明变量
(void)
(^loggerBlock)(void);
// 定义
loggerBlock = ^{
NSLog(@”Hello
world”);
};
// 调用
loggerBlock();
dispatch_async(dispatch_get_global_queue(0,0),
^{
// something
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// something
});
dispatch_async(dispatch_get_main_queue(), ^{
// something
});
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// code to be executed once
});
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_turls_queue
= dispatch_queue_create(“blog.devtang.com”, NULL);
dispatch_async(urls_queue,
^{
// your code
});
dispatch_release(urls_queue);
dispatch_group_t
group = dispatch_group_create();
dispatch_group_async(group,
dispatch_get_global_queue(0,0),^{
//
并行执行的线程一
});
dispatch_group_async(group,
dispatch_get_global_queue(0,0),^{
//
并行执行的线程二
});
dispatch_group_notify(group,
dispatch_get_global_queue(0,0),^{
// 汇总结果
});