GCD
全称:Grand Central Dispatch
Grand Central Dispatch (GCD)是发的一个多核编程的解决方法。在iOS4.0开始之后才能使用。GCD是一个替代诸如NSThread, NSOperationQueue, NSInvocationOperation等技术的很高效和强大的技术。
常用的方法用dispatch_async和dispatch_group_async的使用
以下是两种方法的使用
第一种方法
[super viewDidLoad];
//第一种方法
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//NSLog(@"耗时操作%@",[NSThread currentThread]);
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic11.nipic.com/20101127/4357292_141605011689_2.jpg"]];
UIImage *image=[UIImage imageWithData:data];
//返回主线程
dispatch_async(dispatch_get_main_queue(), ^{
//NSLog(@"更新UI%@",[NSThread currentThread]);
imageView.image=image;
});
});
//第二种方式:
UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(50, 50, 50, 50)];
[self.view addSubview:imageView];
UIImageView *imageView1=[[UIImageView alloc]initWithFrame:CGRectMake(50, 100, 50, 50)];
[self.view addSubview:imageView1];
UIImageView *imageView2=[[UIImageView alloc]initWithFrame:CGRectMake(50,150, 50, 50)];
[self.view addSubview:imageView2];
UIImageView *imageView3=[[UIImageView alloc]initWithFrame:CGRectMake(50, 200, 50, 50)];
[self.view addSubview:imageView3];
//组
//创建组:用于存放耗时操作
__block UIImage *image1,*image2,*image3;
//将操作封装进组,第一个参数代表要存放操作的组名,第二个参数代表操作队列,block执行耗时操作
dispatch_group_t group=dispatch_group_create();
dispatch_group_async(group,dispatch_get_global_queue(0, 0) , ^{
NSData *data=[NSDatadataWithContentsOfURL:[NSURLURLWithString:@"http://pic11.nipic.com/20101127/4357292_141605011689_2.jpg"]];
image1=[UIImage imageWithData:data];
NSLog(@"--1%@",image1);
});
dispatch_group_async(group,dispatch_get_global_queue(0, 0) , ^{
NSData *data=[NSDatadataWithContentsOfURL:[NSURLURLWithString:@"http://pic11.nipic.com/20101127/4357292_141605011689_2.jpg"]];
image2=[UIImage imageWithData:data];
//NSLog(@"--2%@",image2);
});
dispatch_group_async(group,dispatch_get_global_queue(0, 0) , ^{
NSData *data=[NSDatadataWithContentsOfURL:[NSURLURLWithString:@"http://pic11.nipic.com/20101127/4357292_141605011689_2.jpg"]];
image3=[UIImage imageWithData:data];
// NSLog(@"--3%@",image3);
});
//监听一组操作,第一个代表要监听的组名,第二个参数代表一组操作完全结束后跳转到那个队列,一般调到主线程(dispatch_get_main_queue)block执行要进行的操作(一般用来更新UI),注意:此方法在组中的所有操作执行完毕后调用(等待组中的任务执行完毕,回到主线程执行block回调)
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
imageView1.image=image1;
imageView2.image=image2;
imageView3.image=image3;
});