我对 IOS 很陌生。我想在 viewDidLoad 中获取设备上的所有图片。但是该 block 总是在我在代码中调用 NSLog(@"%d", photos.count) 之后执行,如下所示。这种情况如何处理?
__block NSMutableArray* photos = [[[NSMutableArray alloc] init] retain];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
void (^assertsEnumerator)(ALAsset *, NSUInteger , BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop)
{
if(result)
{
NSLog(@"Assert name : %@", [result valueForProperty:ALAssetPropertyURLs]);
[photos addObject:[UIImage imageWithCGImage:[result aspectRatioThumbnail]]];
}
};
void (^groupEnumerator)(ALAssetsGroup*, BOOL*) = ^(ALAssetsGroup *group, BOOL *stop) {
if(group != nil) {
NSLog(@"Adding group %@", [group valueForProperty:ALAssetsGroupPropertyName]);
[group enumerateAssetsUsingBlock: assertsEnumerator];
}
};
[library enumerateGroupsWithTypes: ALAssetsGroupSavedPhotos
usingBlock:groupEnumerator
failureBlock:^(NSError * err) {NSLog(@"Erorr: %@", [err localizedDescription]);}];
[library release];
NSLog(@"%d", photos.count);
[photos release];
Best Answer-推荐答案 strong>
作为 ALAssetsLibrary documentation状态,enumerateGroupsWithTypes:usingBlock:failureBlock: 是异步的,所以不是在原地调用,而是计划在下一个运行循环周期内调用。文档清楚地说明了这是什么原因以及您应该如何进行:
This method is asynchronous. When groups are enumerated, the user may be asked to confirm the application's access to the data; the method, though, returns immediately. You should perform whatever work you want with the assets in enumerationBlock.
关于ios - block 的执行总是延迟,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/9478456/
|