多线程之GCD的线程间通信

从子线程回到主线程

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^{});
//
//  ViewController.m
//  GCD线程间的通信
//
//  Created by wenjim on 17/4/11.
//  Copyright © 2017年 WenJim. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@property (nonatomic,strong) UIImageView * imageView;

@property (nonatomic,strong) UIButton * clickBtn;

@end

@implementation ViewController

-(UIImageView *)imageView
{
    if (!_imageView) {
        _imageView = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width / 2 - 80, self.view.bounds.size.height / 2 - 150, 160, 160)];
        _imageView.backgroundColor = [UIColor redColor];
        _imageView.clipsToBounds = YES;
        _imageView.contentMode = UIViewContentModeScaleAspectFill;
        
    }
    return _imageView;
}

-(UIButton *)clickBtn
{
    if (!_clickBtn) {
        _clickBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _clickBtn.frame = CGRectMake(self.view.bounds.size.width / 2 - 40, self.view.bounds.size.height  - 80, 80, 20);
        [_clickBtn setTitle:@"下载" forState:UIControlStateNormal];
        [_clickBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [_clickBtn addTarget:self action:@selector(setDownloadBtn:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _clickBtn;
}

- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    [self setUpAllControls];
}


#pragma mark - UI控件布局
-(void)setUpAllControls
{
    [self.view addSubview:self.imageView];
    
    [self.view addSubview:self.clickBtn];
}

-(void)setDownloadBtn:(UIButton *)clickBtn
{
    // 1. 创建子线程下载图片
    // DISPATCH_QUEUE_PRIORITY_DEFAULT 0
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        // 下载图片
        // 1.1 URL
        NSURL * url = [NSURL URLWithString:@"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1491485515021&di=b71bf37fbc13415e74dfe073a9fa6154&imgtype=0&src=http%3A%2F%2Ffun.youth.cn%2Fyl24xs%2F201608%2FW020160824572760273145.png"];
        
        // 1.2 根据URL下载图片 二进制数据 到本地
        NSData * data = [NSData dataWithContentsOfURL:url];
        
        // 1.3 转换图片
        UIImage * image = [UIImage imageWithData:data];
        
        NSLog(@"downloadImage------%@",[NSThread currentThread]);
        
        // 更新ImageView的图片
        //异步执行
//        dispatch_async(dispatch_get_main_queue(), ^{
        // 同步执行
        dispatch_sync(dispatch_get_main_queue(), ^{
            
            self.imageView.image = image;
            
            NSLog(@"UI----%@",[NSThread currentThread]);
        });
        
    });
    
}

@end

你可能感兴趣的:(多线程之GCD的线程间通信)