我們在編程的時候會經常會出現這樣的需求:同時請求幾個接口回調成功以後在統一刷新UI,解決這個問題的方法有很多今天我們就說明下GCD下解決的方式。
GCD的leave和enter
//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");
});
這兩種方式都可以達到併發處理的效果,當然還有其他方式,大家一起學習吧!