Adrian
Adrian

Reputation: 20068

Why is a view controller created twice?

I have the following code inside my AppDelegate::didFinishLaunchingWithOptions:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    createContainer { container in
        let storyboard = self.window?.rootViewController?.storyboard

        guard let vc = storyboard?.instantiateViewController(withIdentifier: "Main") as? MainViewController else {
            fatalError("Cannot instantiate root view controller")
        }

        vc.context = container.viewContext
        self.window?.rootViewController = vc
    }

    return true
}

My MainViewController is created at startup, the stack shows the following:

0 MainViewController.viewDidLoad()
UIApplicationMain
main
start

And then is created inside the following line:

self.window?.rootViewController = vc

This is the first time I am seeing a vc created twice.
Is this normal ?
Is there I way I can prevent this ?

Upvotes: 1

Views: 164

Answers (1)

rob mayoff
rob mayoff

Reputation: 385600

UIApplicationMain automatically instantiates the initial view controller of your main storyboard before you receive the application:didFinishLaunchingWithOptions: message. You shouldn't be instantiating it “manually” in application:didFinishLaunchingWithOptions:.

Upvotes: 3

Related Questions