GCD线程间通信

Posted on 2016-07-16 21:34  柠檬片  阅读(146)  评论(0)    收藏  举报
  • 从子线程回到主线程

    dispatch_async(

    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // 执行耗时的异步操作...

          dispatch_async(dispatch_get_main_queue(), ^{

            // 回到主线程,执行UI刷新操作

            });

    });

 

 1 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
 2 {
 3 
 4     //1.开子线程下载图片
 5     //创建队列(并发)
 6     dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
 7     
 8     //异步函数
 9     dispatch_async(queue, ^{
10         
11         //1.获取url地址
12         NSURL *url = [NSURL URLWithString:@"http://www.huabian.com/uploadfile/2015/0914/20150914014032274.jpg"];
13         
14         //2.下载图片
15         NSData *data = [NSData dataWithContentsOfURL:url];
16 
17         //3.把二进制数据转换成图片
18         UIImage *image = [UIImage imageWithData:data];
19         
20         NSLog(@"----%@",[NSThread currentThread]);
21         
22         dispatch_sync(dispatch_get_main_queue(), ^{
23             self.imageView.image = image;
24             NSLog(@"+++%@",[NSThread currentThread]);
25         });
26     });
27 }
示例