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);
网络请求
dispatch_group_leave(downloadGroup);
}
}
dispatch_group_notify(downloadGroup, dispatch_get_main_queue(), ^{
NSLog(@"end");
});
3.使用GCD的信号量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个网络请求顺序回调。
需求需要顺序回调,即执行完第一个网络请求后,第二个网络请求回调才可被执行,简单来讲就是输出得是0,1,2,3...9这种方式的。
NSMutableArray *operationArr = [[NSMutableArray alloc]init];
for (int i=0; i<5; i++) {
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
// 进行网络请求
{
}
//非网络请求
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会阻塞当前线程
#warning - 绝对不要在应用主线程中等待一个Operation,只能在第二或次要线程中等待。阻塞主线程将导致应用无法响应用户事件,应用也将表现为无响应。
5.还是使用信号量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