gpt4 book ai didi

ios - 如何运行异步操作

转载 作者:行者123 更新时间:2023-11-28 15:37:15 25 4
gpt4 key购买 nike

例如,我有这个自定义操作:

class CustomOperation: Operation {

override init() {
super.init()
self.qualityOfService = .userInitiated
}

override func main() {
// ..
}
}

这就是我运行 CustomOperation 所做的事情:

let customOperation = CustomOperation()
customOperation.completionBlock = { print("custom operation finished") }
customOperation.start()

我有几个 CustomOperation 试图同时运行。无论如何要在不为每个 CustomOperation 创建 OperationQueue 的情况下异步运行它?因为 isAsynchronous 属性是只读的。

最佳答案

您不必为每个操作创建一个队列。您可以将它们全部放在同一个队列中。队列的 maxConcurrentOperationCount 确定同时运行的数量。

如果您根本不想使用队列,则需要覆盖 start() 和 isAsynchronous() 并让 start() 启动线程并运行。您需要做的远不止于此(阅读文档)

https://developer.apple.com/reference/foundation/operation

转到“重写方法”部分

If you are creating a concurrent operation, you need to override the following methods and properties at a minimum:

  • start()
  • isAsynchronous
  • isExecuting
  • isFinished

In a concurrent operation, your start() method is responsible for starting the operation in an asynchronous manner. Whether you spawn a thread or call an asynchronous function, you do it from this method. Upon starting the operation, your start() method should also update the execution state of the operation as reported by the isExecuting property. You do this by sending out KVO notifications for the isExecuting key path, which lets interested clients know that the operation is now running. Your isExecuting property must also provide the status in a thread-safe manner.

关于ios - 如何运行异步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44166676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com