我正在使用 Apple 的 ALAssetsLibrary 框架进行一些迭代。我需要在开始播放视频之前完成此迭代。
这里是简化的示例代码,显示了我遇到的问题。
@property (nonatomic) NSMutableArray *assetsToPlay;
- (void)viewDidLoad
{
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
[library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
AVAsset *asset = <#Get Asset#>
[self.assetsToPlay addObject:asset];
}];
} failureBlock:nil];
[self playem]; // BUG: This code is invoked immediately. I would like it to run only after the above block iteration finished.
}
- (void)playem
{
for(AVAsset *asset in self.assetsToPlay) {
NSLog(@"%@", asset);
}
}
最佳答案
就 Elad 而言,枚举方法异步运行,完成后 group
将为 nil
。
因此,与大多数异步情况一样,您应该将调用移至完成 block 中的 playem
内部,而不是在其之后。您想在 group
为 nil
时调用 playem
(即您已完成枚举):
[library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group) {
// if `group` is non-`nil`, then still enumerating the groups
[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result) {
// note, only do this if `result` is not `nil` (`nil` signifies end of asset enumeration)
AVAsset *asset = <#Get Asset#>
[self.assetsToPlay addObject:asset];
}
}];
} else {
// if `group` is `nil`, then done with enumeration, so call method
[self playem]; // this will be called when the enumeration is done.
}
} failureBlock:^(NSError *error) {
// handle the user's rejection of permission here
}];
关于objective-c - 使用 ALAssetsLibrary 枚举 block 强制执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22616098/