请尝试以下操作:
- 创建 NSOperationQueue。设置最大并发任务1。它将执行串行队列模式
- 创建 NSOperation 子类(假设 CustomOperation)并在 main 方法中编写所需的代码。一旦所需的工作完成触发完成并切换到主线程并执行进度条更新事物或其他
- 创建 CustomOperation 的对象并将它们全部添加到第 1 步队列
类CustomOperation:操作{
var identifier:String?
var index:Int?
override func main() {
/// do sync or async tasks
//// post completion tasks
NotificationCenter.default.post(name: NSNotification.Name("TASKDONE"), object: self)
}
}
函数添加操作(){
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.trackOperation(operation:)), name: NSNotification.Name(rawValue: "TASKDONE"), object: nil)
let operationQueue = OperationQueue()
var items = [CustomOperation]()
for index in 0..<10 {
let operation = CustomOperation()
operation.index = index
operation.name = "Operation:\(index)"
items.append(operation)
}
operationQueue.maxConcurrentOperationCount = 1
operationQueue.addOperations(items, waitUntilFinished: false)
}