或者您也可以使用操作队列。在 Swift 3 中:
let queue = OperationQueue()
queue.addOperation() {
// do something in the background
OperationQueue.main.addOperation() {
// when done, update your UI and/or model on the main queue
}
}
无论是这个还是 GCD,Andy illustrated,都可以正常工作。
请参阅 Apple 的 Concurrency Programming Guide,了解操作队列和调度队列(又名 Grand Central Dispatch,GCD)的相对优点。虽然该指南仍在说明使用 Objective-C 的示例,但 API 和概念在 Swift 中基本相同(只需使用 Swift 语法)。 Xcode 中 GCD 和操作队列的文档描述了 Objective-C 和 Swift API。
顺便说一句,您会注意到在上面的示例以及 Andy 的 GCD 演示中,我们都使用了“尾随闭包”。例如,如果您查看addOperationWithBlock 的定义,它被定义为具有一个参数的函数,即“闭包”(类似于 Objective-C 中的块):
func addOperation(_ block: @escaping () -> Swift.Void)
这可能会导致您假设您会按如下方式调用它:
queue.addOperation({
// do something in the background
})
但是当函数的最后一个参数是闭包时,尾随闭包语法允许您将最后的闭包参数从函数的括号中取出,并将其移到函数后面,从而产生:
queue.addOperation() {
// do something in the background
}
因为括号里什么都没有了,你甚至可以更进一步,去掉那些空括号:
queue.addOperation {
// do something in the background
}
希望这能说明如何解释 NSOperationQueue/OperationQueue 和/或 GCD 函数声明并在您的代码中使用它们。