错误“This application is modifying the autolayout engine from a background thread” — 如何修复?
大家好!我是 Swift 和 macOS 开发的新手。遇到了一个奇怪的错误,它并不总是出现,只有当应用程序执行某个耗时操作时才会出现。控制台输出消息:
```
This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.
```
我有一个简单的例子:我在后台线程中从互联网加载数据,完成后想更新屏幕上的 `NSTextField`。这是我的代码:
```swift
import Cocoa
class ViewController: NSViewController {
@IBOutlet weak var statusLabel: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// 模拟长时间加载
DispatchQueue.global().async {
self.loadData()
}
}
func loadData() {
// 模拟加载
Thread.sleep(forTimeInterval: 2.0)
let result = "数据