Inherited initializers are a concern when you create a subclass. Sometimes a superclass init... method sufficiently initializes instances of your class. But because it is more likely it won’t, you should override the superclass’s initializer. If you don’t, the superclass’s implementation is invoked, and because the superclass knows nothing about your class, your instances may not be correctly initialized.
在同一页上我找到了这段文字:
Every object that declares instance variables should implement an initializing method—unless the default set-everything-to-zero initialization is sufficient.
我的问题是: 如果我跳过 B 类中的 init 方法,其中 B 类继承自 A,我可以相信 B 的非继承成员变量被设置为零吗?
最佳答案
My question is: If I skip the init method in class B, where class B inherits from A, can I trust that B's non-inherited member variables are set to zero?
Objective-C 将 set all ivars of any new object to zero :
The alloc method dynamically allocates memory for the new object’s instance variables and initializes them all to 0—all, that is, except the isa variable that connects the new instance to its class. For an object to be useful, it generally needs to be more completely initialized. That’s the function of an init method.
因此,如果您没有任何需要初始化的 ivars/属性,则可以跳过为您的类实现初始化方法。当然,您仍然必须通过调用 -init
或其他一些初始化方法来初始化新对象,以便父类(super class)有机会初始化自己。
关于objective-c - 可以跳过继承类中的 init 方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12628822/