NSOperation实现线程间通信

Posted on 2016-07-17 17:45  柠檬片  阅读(133)  评论(0)    收藏  举报
 1 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 2 {
 3     //1.创建队列
 4     NSOperationQueue *queue= [[NSOperationQueue alloc]init];
 5     
 6     NSBlockOperation *download1 = [NSBlockOperation blockOperationWithBlock:^{
 7         //2.1.确定要下载网络图片的url地址,一个url唯一对应着网络上的一个资源
 8         NSURL *url = [NSURL URLWithString:@"http://p6.qhimg.com/t01d2954e2799c461ab.jpg"];
 9         
10         //2.2.根据url地址下载图片数据到本地(二进制数据)
11         NSData *data = [NSData dataWithContentsOfURL:url];
12         
13         //2.3.把下载到本地的二进制数据转换成图片
14        self.image1 = [UIImage imageWithData:data];
15 
16     }];
17     
18     NSBlockOperation *download2 = [NSBlockOperation blockOperationWithBlock:^{
19         //2.1.确定要下载网络图片的url地址,一个url唯一对应着网络上的一个资源
20         NSURL *url = [NSURL URLWithString:@"http://p6.qhimg.com/t01d2954e2799c461ab.jpg"];
21         
22         //2.2.根据url地址下载图片数据到本地(二进制数据)
23         NSData *data = [NSData dataWithContentsOfURL:url];
24         
25         //2.3.把下载到本地的二进制数据转换成图片
26         self.image2 = [UIImage imageWithData:data];
27         
28     }];
29     
30     NSBlockOperation *combie = [NSBlockOperation blockOperationWithBlock:^{
31         
32         UIGraphicsBeginImageContext(CGSizeMake(200, 200));
33         
34         [self.image1 drawInRect:CGRectMake(0, 0, 200, 100)];
35         [self.image2 drawInRect:CGRectMake(0, 100, 200, 100)];
36         
37         UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
38         
39         UIGraphicsEndImageContext();
40         
41         //刷新UI
42         [[NSOperationQueue mainQueue] addOperationWithBlock:^{
43             self.imageView.image = image;
44             NSLog(@"%@----",[NSThread currentThread]);
45         }];
46 
47     }];
48     
49     [combie addDependency:download1];
50     [combie addDependency:download2];
51     
52     [queue addOperation:download1];
53     [queue addOperation:download2];
54     [queue addOperation:combie];
55 }
示例