在 iOS 4.x 上,我试图枚举设备上的所有照片,当完成后,再以相同的方法进一步处理该列表。
由于 enumerateGroupsWithTypes 的块在另一个线程上异步运行,我看不到如何阻止主线程继续执行,我的解决方案是保持进一步处理从开始直到准备好是轮询我正在收集的照片数组,直到它看到它通过在最后包含一个 NSNull 对象来完成填充。
在 iOS 4.0 上它工作正常——轮询继续,因为另一个线程枚举照片,然后在完成后在主线程上继续执行。在 iOS 4.1+ 上,轮询是如何阻止另一个线程执行它的任何块,因此轮询陷入无限循环。
除了通过将进一步处理分解为枚举块可以调用的不同方法来接受枚举的异步性质之外,是否有更好的方法来实现这一点?
奖励积分:为什么我的投票方法适用于 4.0 而不是 4.1+?
NSMutableArray *photos = [NSMutableArray new];
void (^assetEnumerator)(ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
if(result != NULL) {
[photos addObject:result];
}
};
void (^assetGroupEnumerator)(ALAssetsGroup *, BOOL *) = ^(ALAssetsGroup *group, BOOL *stop) {
if(group != nil)
[group enumerateAssetsUsingBlock:assetEnumerator];
else
[photos addObject:[NSNull null]];
};
ALAssetsLibrary *library = [ALAssetsLibrary new];
[library enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:assetGroupEnumerator
failureBlock:^(NSError *error) {
NSLog(@"%@", error);
}];
// keep polling until the photos have all been enumerated
// (NSNull is the last 'photo' added)
while (![photos count] || ![[photos objectAtIndex:[photos count]-1] isEqual:[NSNull null]]);
// ... further processing ...