從子線程回到主線程
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. 創(chuàng)建子線程下載圖片
// 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 根據(jù)URL下載圖片 二進(jìn)制數(shù)據(jù) 到本地
NSData * data = [NSData dataWithContentsOfURL:url];
// 1.3 轉(zhuǎn)換圖片
UIImage * image = [UIImage imageWithData:data];
NSLog(@"downloadImage------%@",[NSThread currentThread]);
// 更新ImageView的圖片
//異步執(zhí)行
// dispatch_async(dispatch_get_main_queue(), ^{
// 同步執(zhí)行
dispatch_sync(dispatch_get_main_queue(), ^{
self.imageView.image = image;
NSLog(@"UI----%@",[NSThread currentThread]);
});
});
}
@end
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。