How to reorganize my code to call AppDelegate in the main thread?

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

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

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

Note . Using a block DispatchQueue.main.async{}from anywhere access is made is appDelegatenot a parameter. You must use it only in the ad static var appDelegate.

Look for a smart workaround.

Corresponding alarm message:

Main Thread Checker: UI API invoked in the background thread: - [UIApplication delegate] PID: 1094, TID: 30824, Thread name: (none), Queue name: NSOperationQueue 0x60400043c540 (QOS: UNSPECIFIED), QoS: 0

+4
source share
2 answers

Solved using send 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!;
}

and call him elsewhere for

let appDelegate = AppDelegate(). realDelegate!
+5
source

A possible solution is to make the appDelegateclass property appDelegatethat is initialized when the application delegate is created as static storage :

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    static var appDelegate: AppDelegate!

    override init() {
        super.init()
        AppDelegate.appDelegate = self
    }

    // ...
}

Then the application delegate can be found as

 AppDelegate.appDelegate

from any stream.

( UIApplicationMain(), , , .)

+3

Source: https://habr.com/ru/post/1684273/


All Articles