gpt4 book ai didi

iphone - __block 变量未保留

转载 作者:行者123 更新时间:2023-11-28 17:38:48 25 4
gpt4 key购买 nike

我正在尝试将 block 内的结果分配给 block 变量。这是我的代码:

__block UIImage *latestImage;
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];

// Enumerate just the photos and videos group by using ALAssetsGroupSavedPhotos.
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos
usingBlock:^(ALAssetsGroup *group, BOOL *stop){
// Within the group enumeration bl ock, filter to enumerate just photos.
[group setAssetsFilter:[ALAssetsFilter allPhotos]];

// Chooses the photo at the last index
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:([group numberOfAssets]-1)]
options:0
usingBlock:^(ALAsset *alAsset, NSUInteger index, BOOL *innerStop){
// the end of the enumeration is signaled by asset == nil.
if (alAsset){
ALAssetRepresentation *representation = [alAsset defaultRepresentation];
latestImage = [UIImage imageWithCGImage:[representation fullResolutionImage]];
}
}];
}
failureBlock: ^(NSError *error){
// handle error
NSLog(@"No groups");
}
];
return latestImage;

我通过在 block 内的 UIImageView 上显示它来确认变量 latestImage 已设置在 block 内。但是,当我尝试如上面的代码所示返回该对象时,它什么也没有返回。

我错过了什么?

谢谢。

最佳答案

enumerateGroupsWithTypes:usingBlock:failureBlock: 是异步的。您在 block 有机会设置变量之前返回 latestImage。来自 ALAssestsLibrary 的文档:

Many of the methods declared by ALAssetsLibrary take a failure block as an argument. These methods are all asynchronous, because the user may need to be asked to grant access to the data.

您可以将整个函数包装在 dispatch_sync() 中,或者使用信号量来等待答案。无论哪种方式,请确保您没有在主线程上执行此操作。

关于iphone - __block 变量未保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8958635/

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