如何重构代码以在主线程上调用AppDelegate? [英] How do I refactor my code to call AppDelegate on the main thread?

查看:116
本文介绍了如何重构代码以在主线程上调用AppDelegate?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始将项目从Swift3/Xcode8迁移到Swift4/Xcode9.我的应用程序在运行时崩溃,因为主线程清理程序仅允许在主线程上访问UIApplication.shared.delegate,从而导致启动时崩溃.我有以下代码,在Swift 3中效果很好-

I recently started migrating my project from Swift3/Xcode8 to Swift4/Xcode9. My app crashes at runtime because the main thread sanitizer allows access to UIApplication.shared.delegate only on the main thread, resulting in a crash at startup. I have the following code, which worked fine in Swift 3 -

static var appDelegate: AppDelegate {
    return UIApplication.shared.delegate as! AppDelegate;
}

我代码中的其他类可以访问appDelegate.我需要找出一种从主线程返回UIApplication.shared.delegate的方法.

Other classes in my code make access to appDelegate. I need to figure out a way to return UIApplication.shared.delegate from the main thread.

注意:从任何地方访问appDelegate的地方都不能使用DispatchQueue.main.async{}块.只需要在static var appDelegate声明中使用它.

Note: Using an DispatchQueue.main.async{} block from wherever access is made to appDelegate is not an option. Need to use it only within the static var appDelegate declaration only.

寻找一个聪明的解决方法.

Looking for a clever workaround.

相关的崩溃消息:

主线程检查器:在后台线程上调用的UI API:-[UIApplication委托] PID:1094,TID:30824,线程名称:(none),队列名称:NSOperationQueue 0x60400043c540(QOS:469),QoS:0

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

推荐答案

使用调度组解决.

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!

这篇关于如何重构代码以在主线程上调用AppDelegate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆