Swift dispatch_group在递归函数调用时的奇怪行为

时间:2015-07-28 20:11:16

标签: ios swift recursion grand-central-dispatch dispatch-async

我正在下载一堆图片,并在下载了所有这些图片后执行回调 。为此,我使用的是dispatch_group API。

因为我使用的缓存库有一些错误(他们不会很快修复它,所以不能更改)我正在分批操作(50张图像,然后是50张其他图像)。

添加递归调用时行为出错:

dispatch_group_notify(downloadGroup, dispatch_get_main_queue()) {

    // This works perfectly, get called ONCE after ALL images are downloaded    
    // finishedCallback?(images: images, errors: errors)


    // This snippet doesn't work. I don't understand why but it gets called
    // MULTIPLE times instead of once, like the like above
    if (index + maxDownloadsPerRequest) >= Int(total) {
        finishedCallback?(images: images, errors: errors)
    } else {
        self.callMyselfRecursively(#updatedIndex: index)
    }
}

知道我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:0)

你可以尝试屏障:

dispatch_queue_t queue = dispatch_queue_create("custom_queue", DISPATCH_QUEUE_CONCURRENT);
dispatch_async(queue, ^{
  // download image here
});

// call this line when you started all workers
dispatch_barrier_sync(queue, ^{
  // do something then all workers finished
});