初始化编码器aDecoder到底是什么? [英] What exactly is init coder aDecoder?

查看:106
本文介绍了初始化编码器aDecoder到底是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从在线课程中学习iOS开发,每次我创建自定义视图(自定义表格视图单元格,集合视图单元格等)时,讲师始终会实现此初始化程序:

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)
}

为什么我总是必须打电话给我?它有什么作用?我可以将属性放在init内吗?

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

推荐答案

我将从相反的方向开始回答:如果要将视图状态保存到磁盘上怎么办?这称为序列化.相反的是反序列化-从磁盘恢复对象的状态.

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.

NSCoding协议定义了两种方法来序列化和反序列化对象:

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
}

那么为什么在您的自定义类中需要它?答案是Interface Builder.将对象拖到情节提要板上并对其进行配置时,Interface Builder会将该对象的状态序列化到磁盘上,然后在屏幕上出现情节提要时反序列化该对象.您需要告诉Interface Builder如何执行这些操作.至少,如果您不向子类添加任何新属性,则可以简单地要求超类为您进行打包和解包,因此调用super.init(coder: aDecoder).如果子类比较复杂,则需要为子类添加自己的序列化和反序列化代码.

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.

这与Visual Studio的方法相反,Visual Studio的方法是将代码写入隐藏文件中,以在运行时创建对象.

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.

这篇关于初始化编码器aDecoder到底是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆