3

我正在尝试从照片库中提取所有图像。问题是该方法[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?有任何想法吗?

4

1 回答 1

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
    }
};
于 2013-02-25T18:09:27.553 回答