How do View Controllers fit in to the iOS app lifecycle?
I was reading ahead about iOS app lifecycles trying to wrap my head around how apps function. From what I read it seems like the "AppDelegate" controls what and when certain things happen in the app. How do View Controllers link up to the AppDelegate (or something else if thats not the class to manage it)? In AppDelegate I never even see anything mentioning views in the default code. Hopefully my question makes sense. Thanks!
Here is the documentation I was reading: https://developer.apple.com/library/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/TheAppLifeCycle/TheAppLifeCycle.html
The reason you do not see any code related to the view controller in the AppDelegate.swift code is because it is being handled by iOS (UIKit framework) on your behalf (although it can also be done programmatically as well).
There doesn't seem to be a resource that definitively answers your question, however I've managed to piece together a few sources that should give you a better idea as to what is happening under the hood.
The UIWindow Class Reference says the following:
"Providing your app’s main window is easy because Xcode does it for you. New iOS projects use storyboards to define the app’s views. Storyboards require the presence of a window property on the app delegate object, which the Xcode templates automatically provide. Thus with no effort on your part, new projects have a main window in which to display their view controller content."
Also, if you look at the "App Programming Guide for iOS", there is a diagram showing "The Launch Cycle" of an app. Here is a link: App Programming Guide for iOS. This diagram alludes to how the initial view is displayed and thus how the view controller is made available to respond to events from the user.
Putting this all together, I would summarize the following:
- During the launch of your app, iOS determines which storyboard to use as the "main" storyboard (based on the settings in the Info.plist)
- A UIWindow object is instantiated and is used to set the window property on the AppDelegate class
- The rootViewController property of the window property is set to the initial view controller in the "main" storyboard
- The window is made visible and the view is displayed
- The application:didFinishLaunchingWithOptions: function is then called.
- The view controller is now available to respond to events
For more details on how the view controller fits into your app's lifecycle, I found this book (Learning iOS UI Development by Yari D'areglia) to be very helpful in filling in the gaps of Apple's documentation. Specifically the section titled "Configuring windows" in Chapter 1.
Hopefully some other folks on Treehouse could provide more detail or refine my explanation. Hope this helps :)