Why Do View Controllers Need init(coder:)?
If you've ever tried using UIKit, you know you need to create a view controller that conforms to the UIViewController
superclass.
You finish coding everything, but then it frustratingly fails to build!
This error usually appears when writing code-based view controllers (and not using storyboards or XIBs).
So, why does this happen?
The class UIViewController conforms to NSCoding
protocol.
Since our code-based approach requires using UIViewController
, we must conform to its protocol, which includes implementing a required initializer, even if we don't use it directly.
What is NSCoding
A protocol enables an object to be encoded and decoded for archiving and distribution [1].
But what does this mean exactly?
This means that you can use this protocol to encode or decode objects, similar to what you already do when you conform to Codable
or use third-party frameworks.
Why is NSCoding Necessary for Storyboards?
Now, here's the big question: why should we care about coding and encoding when building a UI? 🤨
Even when we create view controllers programmatically, we still need to use a UIStoryboard
to specify the name and bundle information.
At runtime, UIStoryboard
creates the view controller programmatically by encoding them by, you guessed it, using the NSCoding
protocol.
During the instantiation process,UIStoryboard
creates your view controller programmatically using itsinit(coder:)
method. The storyboard passes the view controller’s data archive to that method, which then uses the data to recreate the state of the view controller and its views [2].
Wrap-Up
Now that you know why this initializer is required when you create a view controller programmatically, let's review this with a diagram.
I hope you found this article insightful and now understand the importance of implementing this initializer, even if you don't directly use it.
Thank you for reading.
References
[1] NSCoding: https://developer.apple.com/documentation/foundation/nscoding
[2] Storyboard: https://developer.apple.com/documentation/uikit/uistoryboard