Xcode UIView.init(frame :)必须仅在主线程中使用 [英] Xcode UIView.init(frame:) must be used from main thread only
问题描述
我正在尝试在后台线程中渲染一些视图,以不影响主线程.在Xcode 9之前,这从来都不是问题.
I'm trying to render some views in background thread to not affect the main thread. That was never a problem before Xcode 9.
DispatchQueue.global(qos: .background).async {
let customView = UIView(frame: .zero)
DispatchQueue.main.async {
self.view.addSubview(customView)
}
}
只能从主线程使用UIView.init(frame:)
UIView.init(frame:) must be used from main thread only
此错误发生在第二行.
更新
Apple UIView
文档实际上在线程注意事项部分中说:
The Apple UIView
Documentation actually says in the Threading Considerations section:
对应用程序用户界面的操作必须在主线程上进行.因此,您应该始终从应用程序主线程中运行的代码调用UIView类的方法. 唯一不必严格要求的时间是在创建视图对象本身时,但是所有其他操作都应在主线程上进行.
推荐答案
Xcode 9 has a new runtime Main Thread Checker that detects call to UIKit from a background thread and generate warnings.
我知道它的意思是生成警告而不会使应用程序崩溃,但是您可以尝试为测试目标禁用主线程检查器.
I know its meant to generate warnings and not crash the app, but you can try disabling Main Thread Checker for your test target.
我在一个示例项目中尝试了此代码,调试器在该问题上暂停了(如预期的那样),但该应用程序并未崩溃.
I tried this code in a sample project, the debugger paused at the issue (as it is supposed to), but the app didn't crash.
override func viewDidLoad() {
super.viewDidLoad()
DispatchQueue.global().async {
let v = UIView(frame: .zero)
}
}
这篇关于Xcode UIView.init(frame :)必须仅在主线程中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!