线程间通讯

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

示例场景:子线程下载网络图片,回主线程更新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     });

NSOperation示例代码:

 1 - (void)block2
 2 {
 3     // 创建队列:默认并发队列
 4     NSOperationQueue *queue = [[NSOperationQueue alloc] init];
 5     
 6     // 直接添加操作到队列中:默认是异步的
 7     [queue addOperationWithBlock:^{
 8         
 9         NSLog(@"downloading。。。%@",[NSThread currentThread]);
10         
11         // 下载成功,回到主线程更新ui
12         [[NSOperationQueue mainQueue] addOperationWithBlock:^{
13             NSLog(@"download success--%@",[NSThread currentThread]);
14         }];
15         
16     }];
17 }
原文地址:https://www.cnblogs.com/panda1024/p/6265882.html