Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

ios - What exactly is init coder aDecoder?

I'm learning iOS development from an online course and everytime I make a custom view (custom table view cell, collection view cell, etc) the instructor always implements this initializer:

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
}

Why exactly do I always have to call this? What does it do? Can I put properties inside the init?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...