objcio / core-data

Sample code for the objc.io Core Data book
https://www.objc.io/books/core-data
MIT License
770 stars 198 forks source link

Initial ViewController Loading twice? #38

Open tobhae-dev opened 7 years ago

tobhae-dev commented 7 years ago

In AppDelegate the Main-Storyboard and initial VC is initiated and configured. Also in the App-Info.plist the App is configured to automatically load the Main-Storyboard [with its initialViewController].

So my Question: Is the Main-Storyboard and ViewController loaded twice?

evandelaney commented 6 years ago

There are two instances of the UIStoryboard object (once initialized by the system and again programmatically in applicationDidFinishLaunching...). Both instances have the same values.

The initial view controller in Main.storyboard is a plain ol' UIViewController. I believe this is a placeholder view controller to display on screen while the Core Data stack is being set up.

The view controller with the identifier "RootViewController" that is instantiated in AppDelegate is the primary flow of the app. The window's root view controller starts off as the storyboard initial view controller but then is programmatically replaced.

        createMoodyContainer { container in
            self.persistentContainer = container
            self.syncCoordinator = SyncCoordinator(container: container)

// 2nd initialization of a storyboard object. Will be dealloc'd by end of closure.
// Could have done something like let sb = self.window?.rootViewController.storyboard, but
// that would have returned an optional as well as breaking the Law of Demeter guideline.
            let storyboard = UIStoryboard(name: "Main", bundle: nil)

// creating an instance of RootViewController
            guard let vc = storyboard.instantiateViewController(withIdentifier: "RootViewController") as? RootViewController else { fatalError("Wrong view controller type") }
            vc.managedObjectContext = container.viewContext

// Assigning the RootViewController instance to UIWindow's rootViewController property
// effectively "swaps in" the main UI/UX of the app.
            self.window?.rootViewController = vc