原文來自pianzhidenanren的AFNetworking+GCD處理并發(fā)問題
我們?cè)诰幊痰臅r(shí)候會(huì)經(jīng)常會(huì)出現(xiàn)這樣的需求:同時(shí)請(qǐng)求幾個(gè)接口回調(diào)成功以后在統(tǒng)一刷新UI
坦仍,解決這個(gè)問題的方法有很多今天我們就說明下GCD
下解決的方式坞古。
GCD
的leave
和enter
我們利用dispatch_group_t
創(chuàng)建隊(duì)列組,手動(dòng)管理group
關(guān)聯(lián)的block
運(yùn)行狀態(tài),進(jìn)入和退出group
的次數(shù)必須匹配
//1.創(chuàng)建隊(duì)列組
dispatch_group_t group = dispatch_group_create();
//2.創(chuàng)建隊(duì)列
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//3.添加請(qǐng)求
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.隊(duì)列組所有請(qǐng)求完成回調(diào)刷新UI
dispatch_group_notify(group, dispatch_get_main_queue(), ^{
NSLog(@"model:%f",_buyingStrategyModel.leverrisk);
});
GCD
的信號(hào)量dispatch_semaphore_t
這種方式有點(diǎn)類似于通知模式陨帆,是利用監(jiān)聽信號(hào)量來發(fā)送消息以達(dá)到并發(fā)處理的效果,我們來看看代碼:
//創(chuàng)建信號(hào)量
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(@"信號(hào)量為0");
});
這兩種方式都可以達(dá)到并發(fā)處理的效果,當(dāng)然還有其他方式怎披,大家一起學(xué)習(xí)吧!