gpt4 book ai didi

objective-c - assetsLibrary 一个简单的错误?

转载 作者:搜寻专家 更新时间:2023-10-30 20:00:23 32 4
gpt4 key购买 nike

我真的迷路了。为什么我为每个 UIImage 获取两次 NSLog?

 //------ get the images from the camera roll ----------
assets=[[NSMutableArray alloc]init];
NSMutableArray *cameraRollPictures=[[NSMutableArray alloc]init];
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{

NSInteger numberOfAssets = [group numberOfAssets];
NSLog(@"NUM OF IMAGES:%d",numberOfAssets);
if (numberOfAssets > 0)
{


for (int i = 0; i <= numberOfAssets-1; i++)
{

[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:i] options:0 usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
{
UIImage *thumbnail = [UIImage imageWithCGImage:[result thumbnail]];
[assets addObject:thumbnail];
NSLog(@"theObject!!!! -- (%d) %@",i,thumbnail);

//******* for each i its here twice !! ********

}];
}
}

最佳答案

出于某种原因,enumerateAssetsAtIndexes(和 enumerateAssetsUsingBlock)使用 result == nilindex 对 block 进行额外调用== NSNotFound 在枚举的末尾。如果您将 NSLog() 更改为

,这将变得很明显
NSLog(@"i=%d, index=%ld, result=%@", i, (unsigned long)index, result);

然后你会得到输出

NUM OF IMAGES:2
i=0, index=0, result=ALAsset - Type:Photo, URLs:assets-library://asset/asset.PNG?id=...
i=0, index=2147483647, result=(null)
i=1, index=1, result=ALAsset - Type:Photo, URLs:assets-library://asset/asset.PNG?id=...
i=1, index=2147483647, result=(null)

因此您必须检查 result 的值并忽略 nil 值:

for (int i = 0; i <= numberOfAssets-1; i++) {
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:i] options:0 usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
{
if (result != nil) {
UIImage *thumbnail = [UIImage imageWithCGImage:[result thumbnail]];
[assets addObject:thumbnail];
}
}];
}

请注意,您可以将枚举简化为

[group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if (result != nil) {
UIImage *thumbnail = [UIImage imageWithCGImage:[result thumbnail]];
[assets addObject:thumbnail];
}
}];

关于objective-c - assetsLibrary 一个简单的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15096662/

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