使异步块在其他代码之前运行

时间:2012-07-31 23:27:51

标签: objective-c ios xcode

我正在尝试从ALAssetLibrary中获取视频,以便我可以使用它来完成任务。我正在使用块来做到这一点:

NSMutableArray *assets = [[NSMutableArray alloc] init];

library = [[ALAssetsLibrary alloc] init];

NSLog(@"library allocated");

// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos.

[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {

    NSLog(@"Begin enmeration");

    [group setAssetsFilter:[ALAssetsFilter allVideos]];

    NSLog(@"Filter by videos");

    [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[group numberOfAssets]-1]

                            options:0

                         usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop) {

                             NSLog(@"Asset retrieved");

                             if (alAsset) {

                                 ALAssetRepresentation *representation = [alAsset defaultRepresentation];

                                 NSURL *url = [representation url];

                                 AVAsset *recentVideo = [AVURLAsset URLAssetWithURL:url options:nil];

                                 [assets addObject:recentVideo];

                                 NSLog(@"Asset added to array");

                             } 
                         }];
}

AVMutableComposition *composition = [[AVMutableComposition alloc] init];

NSLog(@"creating source");
AVURLAsset* sourceAsset = [assets objectAtIndex:0];

当我运行代码时,块被跳过,当我尝试访问数组中的元素时程序崩溃,因为它不存在。我被告知这是因为这些块是异步的,但我不确定如何让它们在其他所有操作之前运行。 performSelectorOnMainThread听起来像它可能会这样做,但我真的找不到任何解释我将如何这样做的事情。

1 个答案:

答案 0 :(得分:0)

如果你想要

AVMutableComposition *composition = [[AVMutableComposition alloc] init];

NSLog(@"creating source");
AVURLAsset* sourceAsset = [assets objectAtIndex:0];

在枚举group之后发生,然后将其放在第一个Block中,但在枚举之后:

AVMutableComposition *composition = [[AVMutableComposition alloc] init];
__block AVURLAsset* sourceAsset = nil;
[library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop) {

    // snip...

    [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:[group numberOfAssets]-1]
                            options:0
                         usingBlock:^{
                             // snip... 
                         }];
    sourceAsset = [assets objectAtIndex:0];
    // Now do other things that depend on sourceAsset being set 
}];

__block关键字允许将指针设置为块内的新对象;否则,变量不可重新分配。