dispathc_apply 是dispatch_sync 和dispatch_group的關(guān)聯(lián)API.
它以指定的次數(shù)將指定的Block加入到指定的隊列中。并等待隊列中操作全部完成.
NSArray *array = [NSArray arrayWithObjects:@"/Users/chentao/Desktop/copy_res/gelato.ds",
@"/Users/chentao/Desktop/copy_res/jason.ds",
@"/Users/chentao/Desktop/copy_res/jikejunyi.ds",
@"/Users/chentao/Desktop/copy_res/molly.ds",
@"/Users/chentao/Desktop/copy_res/zhangdachuan.ds",
nil];
NSString *copyDes = @"/Users/chentao/Desktop/copy_des";
NSFileManager *fileManager = [NSFileManager defaultManager];
dispatch_async(dispatch_get_global_queue(0, 0), ^(){
dispatch_apply([array count], dispatch_get_global_queue(0, 0), ^(size_t index){
NSLog(@"copy-%ld", index);
NSString *sourcePath = [array objectAtIndex:index];
NSString *desPath = [NSString stringWithFormat:@"%@/%@", copyDes, [sourcePath lastPathComponent]];
[fileManager copyItemAtPath:sourcePath toPath:desPath error:nil];
});
NSLog(@"done");
});
輸出 copy-index 順序不確定,因為它是并行執(zhí)行的(dispatch_get_global_queue是并行隊列),但是done是在以上拷貝操作完成后才會執(zhí)行,因此,它一般都是放在dispatch_async里面(異步)。實際上,這里 dispatch_apply如果換成串行隊列上,則會依次輸出index,但這樣違背了我們想并行提高執(zhí)行效率的初衷