我有一个操作子类和操作队列,maxConcurrentOperationCount = 1。
这将按顺序执行我的操作,我添加它们,这很好,但现在我需要等待,直到所有操作都完成,然后再运行另一个进程。
我试图使用通知组,但由于这是在for循环中运行的,一旦操作被添加到队列中,通知组就会触发。.我如何等待所有操作离开队列,然后再运行另一个进程?
for (index, _) in self.packArray.enumerated() {
myGroup.enter()
let myArrayOperation = ArrayOperation(collection: self.outerCollectionView, id: self.packArray[index].id, count: index)
myArrayOperation.name = self.packArray[index].id
downloadQueue.addOperation(myArrayOperation)
myGroup.leave()
}
myGroup.notify(queue: .main) {
// do stuff here
}
字符串
7条答案
按热度按时间e5nszbig1#
您可以使用操作依赖性在一系列其他操作完成后启动某些操作:
字符串
或者,在iOS 13及更高版本中,您可以使用屏障:
型
jrcvhitl2#
合适的解决方案是KVO
首先在循环之前添加观察者(假设
queue
是OperationQueue
示例)字符串
然后实施
型
编辑:
在Swift 4中,
December属性:
型
并创建观察者
型
由于iOS13和macOS15不推荐使用
operationCount
。替换是观察progress.completedUnitCount
。另一种现代方法是使用
Combine
的KVO发布程序型
zpjtge223#
我使用下一个解决方案:
字符串
i7uq4tfw4#
将最大并发操作数设置为1
字符串
然后每个操作将按顺序执行(好像每个操作都依赖于前一个操作),完成操作将在最后执行。
tquggr8v5#
队列末尾代码参考this link
NSOperation和NSOperationQueue是用于异步任务的非常好用的Foundation框架工具。但有一件事让我很困惑:我如何在所有队列操作完成后运行代码?简单的答案是:使用队列中操作之间的依赖关系(NSOperation的独特功能)。这只是5行代码解决方案。
NSOption依赖技巧使用Swift很容易实现,如下所示:
字符串
qv7cva1a6#
我的解决方案类似于https://stackoverflow.com/a/42496559/452115,但我没有将
completionOperation
添加到主OperationQueue中,而是添加到队列本身。这对我来说很有效:字符串
1hdlvixo7#
我也遇到过这个问题。好吧,GCD已经提供了API:
dispatch_group
,而不是NSOperation,例如:字符串