gpt4 book ai didi

alassetslibrary - 如何在 ALAssetsLibrary 中使用异步枚举器存储 Assets ?

转载 作者:行者123 更新时间:2023-12-02 03:54:42 24 4
gpt4 key购买 nike

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

        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);

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

最佳答案

正如你所说,它是异步的,所以你需要异步地做最后的赋值。当枚举器耗尽 Assets 时,它将返回 nil 作为结果。这只发生一次并且总是作为枚举的最后一个 Action 。所以推荐的模式是:

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
}
};

关于alassetslibrary - 如何在 ALAssetsLibrary 中使用异步枚举器存储 Assets ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13211003/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com