ios - 如何重构我的代码以在主线程上调用 AppDelegate?

标签 ios swift multithreading swift4

我最近开始将我的项目从 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/

相关文章:

multithreading - Crystal 将线程池背后的想法转换为 Fibers/spawn

c++ - PCL : How continue refreshing of a viewer window?

ios - 如何无限每 1 分钟运行一个 iOS 应用程序?

ios - 在 SceneKit 中为 ARKit 应用加载 SketchUp 模型

ios - 防止 UIStepper 为 0?

ios - 如何让 tabBarController 在第二个ViewController加载时自动加载

ios - 全屏 iOS Swift

ios - iOS 上的计时器不起作用

ios - Swift Core Data - 如何更新所有子实体的属性?

java : spawning new thread is causing original thread to halt