for循環(huán)里的異步任務(wù)完成再進(jìn)行其他操作
// 1.創(chuàng)建一個串行隊(duì)列甘晤,保證for循環(huán)依次執(zhí)行
dispatch_queue_t serialQueue = dispatch_queue_create("serialQueue", DISPATCH_QUEUE_SERIAL);
// 2.異步執(zhí)行任務(wù)
dispatch_async(serialQueue, ^{
// 3.創(chuàng)建一個數(shù)目為1的信號量乳绕,用于“卡”for循環(huán)享潜,等上次循環(huán)結(jié)束在執(zhí)行下一次的for循環(huán)
dispatch_semaphore_t sema = dispatch_semaphore_create(1);
for (int i = 0; i<5; i++) {
// 開始執(zhí)行for循環(huán)瓦堵,讓信號量-1基协,這樣下次操作須等信號量>=0才會繼續(xù),否則下次操作將永久停止
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
printf("信號量等待中\(zhòng)n");
// 模擬一個異步任務(wù)
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://github.com"]];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:urlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
// 本次for循環(huán)的異步任務(wù)執(zhí)行完畢,這時候要發(fā)一個信號菇用,若不發(fā)澜驮,下次操作將永遠(yuǎn)不會觸發(fā)
[tampArray addObject:@(i)];
NSLog(@"本次耗時操作完成,信號量+1 %@\n",[NSThread currentThread]);
dispatch_semaphore_signal(sema);
}];
[dataTask resume];
NSLog(@"上傳動態(tài)照片到阿里云成功:%@", fileInfo.filePath);
NSString *imgUrl = fileInfo.object;
[self.imageUrls addObject:imgUrl];
if (self.imageUrls.count == self.imagePaths.count) {
// 上傳動態(tài)照片到阿里云 完成
}
}
NSLog(@"其他操作");
for (NSNumber *num in tampArray) {
NSLog(@"所有操作完成后的操作---> %@\n",num);
}
});
隊(duì)列組處理for循環(huán)里的異步任務(wù)
// 創(chuàng)建隊(duì)列組惋鸥,可以使多個網(wǎng)絡(luò)請求異步執(zhí)行杂穷,執(zhí)行完之后再進(jìn)行操作
dispatch_group_t group = dispatch_group_create();
//創(chuàng)建全局隊(duì)列
dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
dispatch_group_async(group, queue, ^{
// 循環(huán)上傳數(shù)據(jù)
for (int i = 0; i < self.goodsArray.count; i++) {
//創(chuàng)建dispatch_semaphore_t對象
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
[manager POST:urlStr parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// responseObject 返回的數(shù)據(jù)
// 請求成功發(fā)送信號量(+1)
dispatch_semaphore_signal(semaphore);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"%@",error);
// 失敗也請求成功發(fā)送信號量(+1)
dispatch_semaphore_signal(semaphore);
}];
//信號量減1,如果>0卦绣,則向下執(zhí)行亭畜,否則等待
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}
});
// 當(dāng)所有隊(duì)列執(zhí)行完成之后
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// 執(zhí)行下面的判斷代碼
if (state == self.goodsArray.count) {
// 返回主線程進(jìn)行界面上的修改
dispatch_async(dispatch_get_main_queue(), ^{
…….
});
}else{
dispatch_async(dispatch_get_main_queue(), ^{
…..
});
}
});