ios -[UIApplication 委托] 只能从主线程调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45081731/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
-[UIApplication delegate] must be called from main thread only
提问by renraku
This warning leads to a serious problem cause I really can't call the delegate outside of the main thread using Xcode 9 beta 2. Strange thing is that this was working when I was using Xcode 8.3.3.
这个警告导致了一个严重的问题,因为我真的无法使用 Xcode 9 beta 2 在主线程之外调用委托。奇怪的是,当我使用 Xcode 8.3.3 时,这是有效的。
Also I thought it would only be good practice to call delegates from main thread only, isn't it? So why is this causing the app to crash now?
另外我认为只从主线程调用委托是一种很好的做法,不是吗?那么为什么这会导致应用程序崩溃呢?
回答by orkoden
Just call it from the main thread like this.
只需像这样从主线程调用它。
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication delegate] fooBar];
});
Reaching out to your app delegate like this, is a hint that your architecture could use a little cleanup.
像这样联系您的应用程序委托,暗示您的架构可以进行一些清理。
You can call delegates from any thread you want. You only need to make sure you're on the main thread for UIKit calls. Or that you're on the correct thread your CoreData objects expect. It all depends on the API contract your objects have.
您可以从任何您想要的线程调用委托。你只需要确保你在 UIKit 调用的主线程上。或者您在 CoreData 对象期望的正确线程上。这一切都取决于您的对象拥有的 API 合同。
回答by Allen
In Swift, you could also use DispatchQueue.main.async
to call the UI controlling method from the main thread
在 Swift 中,您也可以使用DispatchQueue.main.async
从主线程调用 UI 控制方法
DispatchQueue.main.async {
YourUIControlMethod()
}