【发布时间】:2011-06-20 10:07:04
【问题描述】:
在 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 ...
【问题讨论】:
标签: objective-c ios objective-c-blocks alasset alassetslibrary