AFNetworking+GCD处理并发问题
2018-04-26 本文已影响72人
ZYiDa
原文来自pianzhidenanren的AFNetworking+GCD处理并发问题
我们在编程的时候会经常会出现这样的需求:同时请求几个接口回调成功以后在统一刷新UI
,解决这个问题的方法有很多今天我们就说明下GCD
下解决的方式。
GCD
的leave
和enter
我们利用dispatch_group_t
创建队列组,手动管理group
关联的block
运行状态,进入和退出group
的次数必须匹配
//1.创建队列组
dispatch_group_t group = dispatch_group_create();
//2.创建队列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//3.添加请求
dispatch_group_async(group, queue, ^{
dispatch_group_enter(group);
[HomeRequest getPointBuyAllConfigurationStrategyType:_dataType success:^(NSInteger code, NSDictionary *dict) {
dispatch_group_leave(group);
} failuer:^(NSInteger code, NSString *message) {
dispatch_group_leave(group);
}];
});
dispatch_group_async(group, queue, ^{
dispatch_group_enter(group);
[HomeRequest getStockLeverRiskStockCode:_buyingStrategyModel.stockCode strategyType:_dataType success:^(NSInteger code, NSDictionary *dict) {
dispatch_group_leave(group);
} failuer:^(NSInteger code, NSString *message) {
dispatch_group_leave(group);
}];
});
//4.队列组所有请求完成回调刷新UI
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"model:%f",_buyingStrategyModel.leverrisk);
});
GCD
的信号量dispatch_semaphore_t
这种方式有点类似于通知模式,是利用监听信号量来发送消息以达到并发处理的效果,我们来看看代码:
//创建信号量
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, ^{
[HomeRequest getPointBuyAllConfigurationStrategyType:_dataType success:^(NSInteger code, NSDictionary *dict) {
dispatch_semaphore_signal(semaphore);
} failuer:^(NSInteger code, NSString *message) {
dispatch_semaphore_signal(semaphore);
}];
});
dispatch_group_async(group, queue, ^{
[HomeRequest getStockLeverRiskStockCode:_buyingStrategyModel.stockCode strategyType:_dataType success:^(NSInteger code, NSDictionary *dict) {
dispatch_semaphore_signal(semaphore);
} failuer:^(NSInteger code, NSString *message) {
dispatch_semaphore_signal(semaphore);
}];
});
dispatch_group_notify(group, queue, ^{
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
NSLog(@"信号量为0");
});
这两种方式都可以达到并发处理的效果,当然还有其他方式,大家一起学习吧!