gpt4 book ai didi

SWIFT - OperationQueue.main.addOperation 和 DispatchQueue.main.async 之间有什么区别?

转载 作者:行者123 更新时间:2023-12-02 08:08:40 25 4
gpt4 key购买 nike

有时我必须在主线程上执行某些操作,建议将代码放置在 OperationQueue.main.addOperation 中。

其他时候,建议将代码编写在DispatchQueue.main.async内。

这两者有什么区别?

(有类似的问题标题,但内容不匹配。)

最佳答案

当我在主线程中执行任何任务(例如更新我的APP UI)时,我使用了“DispatchQueue.main.async”。当您需要在主线程中运行进一步的操作或 block 时,可以使用“OperationQueue”。查看这篇文章以了解更多有关OperationQueue的信息

OperationQueue 来自 Apple 文档

The NSOperationQueue class regulates the execution of a set of Operation objects. After being added to a queue, an operation remains in that queue until it is explicitly canceled or finishes executing its task. Operations within the queue (but not yet executing) are themselves organized according to priority levels and inter-operation object dependencies and are executed accordingly. An application may create multiple operation queues and submit operations to any of them.

示例:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var label: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!

override func viewDidLoad() {
super.viewDidLoad()
activityIndicator.startAnimating()
calculate()
}

private func calculate() {
let queue = OperationQueue()
let blockOperation = BlockOperation {

var result = 0

for i in 1...1000000000 {
result += i
}

OperationQueue.main.addOperation {
self.activityIndicator.stopAnimating()
self.label.text = "\(result)"
self.label.isHidden = false
}
}

queue.addOperation(blockOperation)
}

}

DispatchQueue 来自 Apple 文档

DispatchQueue manages the execution of work items. Each work item submitted to a queue is processed on a pool of threads managed by the system.

示例:

URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
print(error ?? "Unknown error")
return
}

do {
let heroes = try JSONDecoder().decode([HeroStats].self, from: data)
DispatchQueue.main.async {
self.heroes = heroes
completed()
}
} catch let error {
print(error)
}
}.resume()

关于SWIFT - OperationQueue.main.addOperation 和 DispatchQueue.main.async 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50972359/

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