一个类什么时候会有多个指定的初始值设定项?
阅读 Apple 关于框架的技巧和技术的文档开发人员,我遇到过这样一个关于指定初始化器的声明:
指定的初始值设定项是调用类的 init 方法 超类的
init
方法。 (其他初始化程序调用init
类定义的方法。)每个公共类都应该有一个或 更多指定的初始值设定项。
(强调。)
根据我的理解(事实上,“指定”一词的使用),一个类应该只有一个指定的初始值设定项。但根据文档,多个指定的初始值设定项是可以接受的。
假设您有两个(或更多)指定初始化程序,它们的作用是调用超类的指定初始化程序以保证正确的对象初始化。但是,如果两个指定初始化器都调用同一个超类的指定初始化器,那么为什么首先需要多个指定初始化器呢?难道不应该重构该类以将所有其他 init
方法集中到单个指定的初始值设定项吗?
我只是有点困惑什么用例或设计模式会需要多个指定的初始值设定项?
Reading through Apple's documentation on Tips and Techniques for Framework Developers, I came across this statement about designated initializers:
A designated initializer is an init method of a class that invokes an
init
method of the superclass. (Other initializers invoke theinit
methods defined by the class.) Every public class should have one or
more designated initializers.
(Emphasis added.)
Based on my understanding—and indeed, the very use of the word "designated"—a class should have only one designated initializer. But according to the documentation, multiple designated initializers are acceptable.
Assuming that you have two (or more) designated initializers, their role is to call the superclass's designated initializer in order to guarantee proper object initialization. But if both designated initializers are calling the same superclass's designated initializer, then why was there the need for more than one in the first place? Shouldn't the class be refactored to funnel all the other init
methods to the singular designated initializer?
I'm just a bit confused as to what use case or design pattern would call for multiple designated initializers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您想要对同一类的不同对象进行不同的初始化时,您可以这样做。一个例子是类簇,例如 NSNumber。它有相当多的初始值设定项,用于它们可以保存的不同类型的数字。为了提供最准确的表示,类应该以与接收它时相同的格式保存它的值,而不是进行强制转换。这意味着初始化器不能简单地调用公共初始化器并返回。他们需要做一些定制工作。这使它们成为指定的初始值设定项。
另一个例子是文档类,它只需要对新文件进行一些初始化,而只需要对正在打开的文档进行一些其他初始化。这两个初始化器都会调用它们的超级实现,而超级实现又调用普通的
init
方法来执行常见的初始化。但是,由于它们不仅仅是简单地使用默认值调用另一个初始值设定项,因此它们被视为指定的初始值设定项。You would do this when you want to have a different initialization for different objects of the same class. One example is class clusters, like NSNumber. It has quite a few initializers for the different types of numbers they can hold. To provide the most accurate representation, the class should hold its value in the same format it received it in, instead of casting. This means the initializers can't simply call a common initializer and return. They need to do some custom work. This makes them a designated initializer.
Another example would be a document class which needs to do some initialization only for new files and some other initialization only for documents being opened. Both of these initializers will call their super implementation, which in turn calls the plain
init
method to do common initialization. However, since they do more than simply calling another initializer with a default value, they are considered designated initializers.