1.使用GCD的dispatch_group_t
dispatch_group_t downloadGroup = dispatch_group_create();
for (int i=0; i<10; i++) {
dispatch_group_enter(downloadGroup);
{
NSLog(@"%d",i);
網(wǎng)絡(luò)請(qǐng)求
dispatch_group_leave(downloadGroup);
}
}
dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{
NSLog(@"end");
});

3.使用GCD的信號(hào)量dispatch_semaphore_t
int count = 0;
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
for (int i=0; i<5; i++) {
NSLog(@"%d---%d",i,i);
count++;
if (count==5) {
dispatch_semaphore_signal(sem);
count = 0;
}
}
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"end");
});

4.考慮新需求,10個(gè)網(wǎng)絡(luò)請(qǐng)求順序回調(diào)。
需求需要順序回調(diào),即執(zhí)行完第一個(gè)網(wǎng)絡(luò)請(qǐng)求后,第二個(gè)網(wǎng)絡(luò)請(qǐng)求回調(diào)才可被執(zhí)行,簡單來講就是輸出得是0,1,2,3...9這種方式的。
NSMutableArray *operationArr = [[NSMutableArray alloc]init];
for (int i=0; i<5; i++) {
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
//? ? ? ? ? ? 進(jìn)行網(wǎng)絡(luò)請(qǐng)求
{
}
//非網(wǎng)絡(luò)請(qǐng)求
NSLog(@"noRequest-%d",i);
}];
[operationArr addObject:operation];
if (i>0) {
NSBlockOperation *operation1 = operationArr[i-1];
NSBlockOperation *operation2 = operationArr[i];
[operation2 addDependency:operation1];
}
}
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[queue addOperations:operationArr waitUntilFinished:NO];? //YES會(huì)阻塞當(dāng)前線程
#warning - 絕對(duì)不要在應(yīng)用主線程中等待一個(gè)Operation,只能在第二或次要線程中等待。阻塞主線程將導(dǎo)致應(yīng)用無法響應(yīng)用戶事件,應(yīng)用也將表現(xiàn)為無響應(yīng)。

5.還是使用信號(hào)量semaphore完成4的需求
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
for (int i=0; i<5; i++) {
NSLog(@"%d",i);
dispatch_semaphore_signal(sem);
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
}
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"end");
});

借鑒?https://mp.weixin.qq.com/s/5nyTIUOcffHHktxDX3nl6A