原文地址:http://blog.csdn.net/pianzhidenanren/article/details/52571853?
我們?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);
[HomeRequestgetPointBuyAllConfigurationStrategyType:_dataTypesuccess:^(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);
[HomeRequestgetStockLeverRiskStockCode:_buyingStrategyModel.stockCodestrategyType:_dataTypesuccess:^(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,?^{
[HomeRequestgetPointBuyAllConfigurationStrategyType:_dataTypesuccess:^(NSInteger?code,NSDictionary*dict)?{
dispatch_semaphore_signal(semaphore);
}failuer:^(NSInteger?code,NSString*message)?{
dispatch_semaphore_signal(semaphore);
}];
});
dispatch_group_async(group,?queue,?^{
[HomeRequestgetStockLeverRiskStockCode:_buyingStrategyModel.stockCodestrategyType:_dataTypesuccess:^(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í)吧腕柜!