多線程之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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容