我最近开始将我的项目从 Swift3/Xcode8 迁移到 Swift4/Xcode9。我的应用程序在运行时崩溃,因为主线程清理器只允许在主线程上访问 UIApplication.shared.delegate
,导致启动时崩溃。我有以下代码,它在 Swift 3 中运行良好 -
static var appDelegate: AppDelegate {
return UIApplication.shared.delegate as! AppDelegate;
}
我代码中的其他类可以访问 appDelegate。我需要找出一种从主线程返回 UIApplication.shared.delegate
的方法。
注意:从访问 appDelegate
的任何地方使用 DispatchQueue.main.async{}
block 不是一种选择。只需要在 static var appDelegate
声明中使用它。
寻找一个聪明的解决方法。
相关崩溃信息:
Main Thread Checker: UI API called on a background thread: -[UIApplication delegate] PID: 1094, TID: 30824, Thread name: (none), Queue name: NSOperationQueue 0x60400043c540 (QOS: UNSPECIFIED), QoS: 0
最佳答案
通过使用 Dispatch Groups 解决。
static var realDelegate: AppDelegate?;
static var appDelegate: AppDelegate {
if Thread.isMainThread{
return UIApplication.shared.delegate as! AppDelegate;
}
let dg = DispatchGroup();
dg.enter()
DispatchQueue.main.async{
realDelegate = UIApplication.shared.delegate as? AppDelegate;
dg.leave();
}
dg.wait();
return realDelegate!;
}
并在其他地方调用它
let appDelegate = AppDelegate(). realDelegate!
关于ios - 如何重构我的代码以在主线程上调用 AppDelegate?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45832155/