I'll start this answer from the opposite direction: what if you want to save the state of your view to disk? This is known as serialization. The reverse is deserialization - restoring the state of the object from disk.
The NSCoding
protocol defines two methods to serialize and deserialize objects:
encodeWithCoder(_ aCoder: NSCoder) {
// Serialize your object here
}
init(coder aDecoder: NSCoder) {
// Deserialize your object here
}
So why is it needed in your custom class? The answer is Interface Builder. When you drag an object onto a storyboard and configure it, Interface Builder serializes the state of that object on to disk, then deserializes it when the storyboard appears on screen. You need to tell Interface Builder how to do those. At the very least, if you don't add any new properties to your subclass, you can simply ask the superclass to do the packing and unpacking for you, hence the super.init(coder: aDecoder)
call. If your subclass is more complex, you need to add your own serialization and deserialization code for the subclass.
This is in contrast to the Visual Studio's approach, which is to write code into a hidden file to make the object at run time.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…