Grand Central Dispatch (GCD)是 Apple 开发的一个多核编程的解决方法。该方法在 Mac OS X 10.6 雪豹中首次推出,并随后被引入到了 iOS4.0 中。GCD 是一个替代诸如 NSThread, NSOperationQueue, NSInvocationOperation 等技术的很高效和强大的技术,它看起来象就其它语言的闭包(Closure)一样,但苹果把它叫做 blocks。
staticNSOperationQueue*queue;-(IBAction)someClick:(id)sender{self.indicator.hidden=NO;[self.indicatorstartAnimating];queue=[[NSOperationQueuealloc]init];NSInvocationOperation*op=[[[NSInvocationOperationalloc]initWithTarget:selfselector:@selector(download)object:nil]autorelease];[queueaddOperation:op];}-(void)download{NSURL*url=[NSURLURLWithString:@"http://www.youdao.com"];NSError*error;NSString*data=[NSStringstringWithContentsOfURL:urlencoding:NSUTF8StringEncodingerror:&error];if(data!=nil){[selfperformSelectorOnMainThread:@selector(download_completed:)withObject:datawaitUntilDone:NO];}else{NSLog(@"error when download:%@",error);[queuerelease];}}-(void)download_completed:(NSString*)data{NSLog(@"call back");[self.indicatorstopAnimating];self.indicator.hidden=YES;self.content.text=data;[queuerelease];}
使用GCD后
如果使用 GCD,以上3个方法都可以放到一起,如下所示:
12345678910111213141516171819
// 原代码块一self.indicator.hidden=NO;[self.indicatorstartAnimating];dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{// 原代码块二NSURL*url=[NSURLURLWithString:@"http://www.youdao.com"];NSError*error;NSString*data=[NSStringstringWithContentsOfURL:urlencoding:NSUTF8StringEncodingerror:&error];if(data!=nil){// 原代码块三dispatch_async(dispatch_get_main_queue(),^{[self.indicatorstopAnimating];self.indicator.hidden=YES;self.content.text=data;});}else{NSLog(@"error when download:%@",error);}});
// 后台执行:dispatch_async(dispatch_get_global_queue(0,0),^{// something});// 主线程执行:dispatch_async(dispatch_get_main_queue(),^{// something});// 一次性执行:staticdispatch_once_tonceToken;dispatch_once(&onceToken,^{// code to be executed once});// 延迟2秒执行:doubledelayInSeconds=2.0;dispatch_time_tpopTime=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});