我正在创建一个这样的串行后台队列:
@property (nonatomic, strong) dispatch_queue_t assetCreationQueue;
// in init...
_assetCreationQueue = dispatch_queue_create("com.mycompany.assetCreationQueue", DISPATCH_QUEUE_SERIAL);
然后我在后台枚举 ALAsset 对象,如下所示:
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop){
if (asset){
dispatch_async(weakSelf.assetCreationQueue, ^{
ALAssetRepresentation *assetRepresentation = [asset defaultRepresentation];
NSURL *url = [assetRepresentation url];
if (url) {
AVURLAsset *avAsset = [[AVURLAsset alloc] initWithURL:url options:nil];
// This NSLog fires! avAsset exists.
NSLog(@"AVURLAsset %@", avAsset);
dispatch_async(dispatch_get_main_queue(), ^{
// This NSLog NEVER fires.
// Also tried dispatch_sync.
NSLog(@"add to assets array on main queue");
[weakSelf.assets insertObject:avAsset atIndex:0];
});
}
});
}
}];
assets 数组属性定义为:
@property (nonatomic, strong) NSMutableArray *assets;
当我尝试时,dispatch_sync(dispatch_get_main_queue(), ^{
我在控制台中只得到一个NSLog(@"AVURLAsset %@", avAsset);
,它表明这dispatch_sync
导致了死锁。
但是我怎样才能找出原因呢?我看不出在哪里。assetCreationQueue 是一个后台队列,我只能在主队列上对数组进行操作。
编辑: 这是一个更加简化的测试,它也失败了:
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop){
if (asset){
dispatch_async(weakSelf.assetCreationQueue, ^{
if ([NSThread isMainThread]) {
NSLog(@"already main thread"); // gets called often!!
} else {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"dispatch async on main queue"); // never gets called!!
});
}
});
}
}];
所以我不明白的是:为什么我已经在主线程上,即使我调用dispatch_async(weakSelf.assetCreationQueue
. 它只能导致邪恶的结论:我创建的队列不是后台队列:
_assetCreationQueue = dispatch_queue_create("com.mycompany.assetCreationQueue", DISPATCH_QUEUE_SERIAL);
为什么?