objective-c - 使用 ALAssetsLibrary 枚举 block 强制执行顺序

标签 objective-c objective-c-blocks

我正在使用 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 内部,而不是在其之后。您想在 groupnil 时调用 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/

相关文章:

c++ - Objective-C block 和 C++ 对象

objective-c - 在 iPhone Simulator 4.3/XCode 4.2 和 4.0.2 中使用 Blocks 会导致应用程序崩溃

iphone - 在 iPhone 应用程序中本地化货币

ios - UIViewController 没有立即出现

ios - 比较数组与不同对象类型的快速方法

objective-c - 您可以将代码附加到 Objective-C block 变量吗?

objective-c - [myArray 添加对象 :[[objcBlock copy] autorelease]] crashes on dealloc'ing the array

ios - XCode Instruments:泄漏NSMallocBlock没有扩展细节的堆栈跟踪

ios - 关闭 dismissViewController 不会触发 viewWillAppear

objective-c - 弱自引用的通用类型