0

我正在尝试从 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 听起来它可能会这样做,但我真的找不到任何解释我将如何这样做的东西。

4

1 回答 1

0

如果你想

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

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

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

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关键字允许将指针设置为块内的新对象;否则变量不可重新分配。

于 2012-07-31T23:48:17.860 回答