Xcode 提示 Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.

提示 Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.,翻译过来大概是「不能在后台线程中改变布局,必须在主线程中才能进行布局操作」。

报错出现的代码是在 URLSession.shared.dataTask 中,符合报错的解释。所以只需要将 Update UI 的代码丢到主线程中去执行:

1
2
3
DispatchQueue.main.async {
// update UI
}

如果是自己创建的子线程,也应该这样操作:

1
2
3
4
5
6
DispatchQueue.global().async {
// 一些比较花时间的操作
DispatchQueue.main.async {
// update UI
}
}

另外,还可能会出现这样的报错:

1
2
Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.
// 不允许从后台线程发布变化;确保在模型更新时从主线程(通过receive(on:)等操作符)发布数值。

解决办法都是一样的。


Xcode 提示 Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.
https://wonderhoi.com/2024/12/12/Xcode-提示-Modifications-to-the-layout-engine-must-not-be-performed-from-a-background-thread-after-it-has-been-accessed-from-the-main-thread/
作者
wonderhoi
发布于
2024年12月12日
许可协议