码迷,mamicode.com
首页 > 编程语言 > 详细

线程间通讯

时间:2017-01-09 18:15:57      阅读:197      评论:0      收藏:0      [点我收藏+]

标签:main   self   blog   jpg   orm   baidu   photo   url   one   

线程间通讯:把一个线程中计算的结果传递到另一个线程中使用。

示例场景:子线程下载网络图片,回主线程更新UI。

 

NSThread示例代码:

 1 - (void)viewDidLoad {
 2     [super viewDidLoad];
 3     
 4     // 子线程下载网络数据
 5     [self performSelectorInBackground:@selector(downloadImage) withObject:nil];
 6 }
 7 
 8 // 加载网络数据,耗时操作,在子线程中进行
 9 - (void)downloadImage {
10     NSURL *url = [NSURL URLWithString:@"http://c.hiphotos.baidu.com/image/pic/item/a044ad345982b2b782d814fd34adcbef76099b47.jpg"];
11     
12     NSData *data = [NSData dataWithContentsOfURL:url];
13     UIImage *img = [UIImage imageWithData:data];
14     
15     NSLog(@"%@-%@",img,[NSThread currentThread]);
16     
17     // 回主线程刷新UI
18     [self performSelectorOnMainThread:@selector(updateUI:) withObject:img waitUntilDone:NO];
19 }
20 
21 // 更新UI
22 - (void)updateUI:(UIImage *)img{
23     self.imgV.image = img;
24     [self.imgV sizeToFit];
25     [self.rootV setContentSize:img.size];
26     
27     NSLog(@"%@-%@",img,[NSThread currentThread]);
28 }

关键代码:

1     // 子线程下载网络数据
2     [self performSelectorInBackground:@selector(downloadImage) withObject:nil];
3     
4     // 回主线程刷新UI:子线程的运算结果传递到主线程中使用
5     [self performSelectorOnMainThread:@selector(updateUI:) withObject:img waitUntilDone:NO];

 

GCD示例代码:

 1 // 子线程下载网络数据
 2     dispatch_async(dispatch_get_global_queue(0, 0), ^{
 3         
 4         // 子线程中执行的代码
 5         NSURL *url = [NSURL URLWithString:@"http://c.hiphotos.baidu.com/image/pic/item/a044ad345982b2b782d814fd34adcbef76099b47.jpg"];
 6         
 7         NSData *data = [NSData dataWithContentsOfURL:url];
 8         UIImage *img = [UIImage imageWithData:data];
 9         
10         NSLog(@"%@-%@",img,[NSThread currentThread]);
11         
12         
13         // 回主线程更新UI
14         dispatch_async(dispatch_get_main_queue(), ^{
15             // 子线程中执行的代码
16             self.imgV.image = img;
17             [self.imgV sizeToFit];
18             [self.rootV setContentSize:img.size];
19             
20             NSLog(@"%@-%@",img,[NSThread currentThread]);
21         });
22     });

 

线程间通讯

标签:main   self   blog   jpg   orm   baidu   photo   url   one   

原文地址:http://www.cnblogs.com/panda1024/p/6265882.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!