GCD线程间通信
//0.获取一个全局的队列
dispatch_queue_tqueue = dispatch_get_global_queue(0,0);
//1.先开启一个线程,把下载图片的操作放在子线程中处理
dispatch_async(queue, ^{
//2.下载图片
NSURL*url = [NSURLURLWithString:@"http://h.hiphotos.baidu.com/zhidao/pic/item/6a63f6246b600c3320b14bb3184c510fd8f9a185.jpg"];
NSData*data = [NSDatadataWithContentsOfURL:url];
UIImage*image = [UIImageimageWithData:data];
NSLog(@"下载操作所在的线程--%@",[NSThreadcurrentThread]);
//3.回到主线程刷新UI
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image= image;
//打印查看当前线程
NSLog(@"刷新UI---%@",[NSThreadcurrentThread]);
});
});
信号量和group结合解决多个请求回来才更新ui
//网络请求都成功才更新UI
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
//创建全局并行
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, queue, ^{
//加载订单消息数据
[[HCViewModel sharedViewModel] loadMessageWithPara:@"1" and:^(NSMutableArray *magerAddressArr) {
dispatch_semaphore_signal(semaphore);
self.orderMessagelistArr = magerAddressArr;
} and:^(NSError *error) {
//请求错误回调
[self hc_failRequestWitherror:error];
}];
});
dispatch_group_async(group, queue, ^{
[[HCViewModel sharedViewModel] loadMessageWithPara:@"2" and:^(NSMutableArray *magerAddressArr) {
dispatch_semaphore_signal(semaphore);
//加载系统消息数据
self.systemMessagelistArr = magerAddressArr;
} and:^(NSError *error) {
//请求错误回调
[self hc_failRequestWitherror:error];
}];
});
dispatch_group_notify(group, queue, ^{
//2个请求对应四次信号等待
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_async(dispatch_get_main_queue(), ^{
//更新UI操作
self.dataList = [NSMutableArray arrayWithObjects:@1,@2, nil];
[self.tableView reloadData];
});
});