首页 > 代码库 > iOS多线程---GCD中线程的通信
iOS多线程---GCD中线程的通信
在子线程的任务完成后,有时候需要从子线程回到主线程,刷新UI。 从子线程中回到主线程,以前已经写过一种方法:
[self.imageView performSelectorOnMainThread:@selector(setImage:) withObject:image waitUntilDone:NO];
现在GCD又提供了一种方法:
dispatch_async(dispatch_get_main_queue(), ^{ self.imageView.image=image; });
示例代码:
// // ViewController.m // GCDTest // // Created by 登 on 2017/6/16. // Copyright ? 2017年 登. All rights reserved. // #import "ViewController.h" @interface ViewController () @property (weak, nonatomic) IBOutlet UIImageView *imageView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSLog(@"主线程----%@",[NSThread mainThread]); } -(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event { //1 获取一个全局队列 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); // 2 把任务添加到队列中执行 dispatch_async(queue, ^{ //打印当前的线程 NSLog(@"%@",[NSThread currentThread]); //3.从网络下载图片 NSURL *urlStr = [NSURL URLWithString:@"http://h.hiphotos.baidu.com/baike/w%3D268/sign=30b3fb747b310a55c424d9f28f444387/1e30e924b899a9018b8d3ab11f950a7b0308f5f9.jpg"]; NSData *data =http://www.mamicode.com/ [NSData dataWithContentsOfURL:urlStr]; UIImage *image = [UIImage imageWithData:data]; //提示 NSLog(@"图片加载完毕"); //4.回到主线程,展示图片 // [self.imageView performSelectorOnMainThread:@selector(setImageView:) withObject:image waitUntilDone:NO]; dispatch_async(dispatch_get_main_queue(), ^{ _imageView.image = image; NSLog(@"%@",[NSThread currentThread]); }); }); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end
打印结果:
2017-06-16 17:55:45.848 GCDTest[15011:2269875] 主线程----<NSThread: 0x60800007f600>{number = 1, name = main}
2017-06-16 17:56:43.391 GCDTest[15011:2269966] <NSThread: 0x60000026b980>{number = 3, name = (null)}
2017-06-16 17:56:43.463 GCDTest[15011:2269966] 图片加载完毕
2017-06-16 17:56:43.463 GCDTest[15011:2269875] <NSThread: 0x60800007f600>{number = 1, name = main}
本文参考:http://www.cnblogs.com/wendingding/p/3807265.html
iOS多线程---GCD中线程的通信
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。