我有一个PHAsset列表,我需要获取相关的URL并对每个URL执行一些操作。处理完所有资产后,我需要执行另一项任务。我尝试使用__block来计算处理的资产,但由于竞争条件,它不可靠。有没有更好的方法来了解何时处理所有资产?
PHFetchResult* photosAsset = [PHAsset fetchAssetsInAssetCollection:collection options:fetchOptions2];
__block int count = 0;
for (int i = 0; i < photosAsset.count; ++i) {
[[PHImageManager defaultManager] requestAVAssetForVideo:[photosAsset objectAtIndex:i] options:nil resultHandler:
^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
NSURL *url = [(AVURLAsset *)avAsset URL];
// then do something with the url here...
++count;
NSLog(@"%d", count);
if (count == photosAsset.count) {
NSLog(@"FINISHED!");
}
}];
}
答案 0 :(得分:0)
所以这是基于@ Larme建议的解决方案:
dispatch_group_t group = dispatch_group_create();
for (int i = 0; i < photosAsset.count; ++i) {
dispatch_group_enter(group);
[[PHImageManager defaultManager] requestAVAssetForVideo:[photosAsset objectAtIndex:i] options:nil resultHandler:
^(AVAsset *avAsset, AVAudioMix *audioMix, NSDictionary *info) {
dispatch_group_leave(group);
}];
}
dispatch_group_notify(group,dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
NSLog(@"FINISHED!");
});
dispatch_release(group);