如何在ALAssetsLibrary中使用异步枚举器存储资产?

时间:2012-11-03 16:15:56

标签: alassetslibrary

我正在尝试从照片库中提取所有图像。问题是方法[ALAssetsGroup enumerateAssetsUsingBlock:]是异步的,所以当我尝试使用资产时,枚举器还没有开始填充我的资产数组。这是我的代码:

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

        void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
            if(result != nil) {
                if(![assetURLDictionaries containsObject:[result valueForProperty:ALAssetPropertyURLs]]) {
                    if(![[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo]) {
                        UIImage* img = [UIImage imageWithCGImage:[[result defaultRepresentation] fullScreenImage]];

                        MyPhoto *photo;
                        photo = [MyPhoto photoWithImage:img];
                        [photos addObject:photo];
                    }
                }
            }
        };

        [[assetGroups objectAtIndex:1] enumerateAssetsUsingBlock:assetEnumerator];

        self.photos = photos;
        NSLog(@"Self.Photos %@", self.photos);

此块运行后self.photos为空。我猜是因为枚举器块在另一个线程中执行,而photos在赋值self.photos = photos中是空的?有什么想法吗?

1 个答案:

答案 0 :(得分:1)

正如您所说,它是异步的,因此您需要异步执行最终分配。当枚举器耗尽资产时,结果将返回nil。这恰好发生一次,并始终作为枚举的最后一个动作。所以推荐的模式是:

void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
    if(result != nil) {
        // ... process result ...
        [photos addObject:photo];
    }
    else {
        // terminating
        self.photos = photos
        NSLog(@"Self.Photos %@", self.photos);

        // you can now call another method or do whatever other post-assign action here
    }
};