objective-c - 可以跳过继承类中的 init 方法吗?

标签 objective-c initialization

考虑 http://developer.apple.com/library/ios/#documentation/general/conceptual/CocoaEncyclopedia/Initialization/Initialization.html 中的以下文本.

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/

相关文章:

ios - 错误: near "?": syntax error using sqlite and obj-c

objective-c - 如何从 cocoa 中的另一个文件设置对象的属性?

c - 在 C 中用两个字符串初始化一个 const char * const *

java - 当使用设置的默认值启动 Popupwindow 时出现 NullPointerException,否则它可以工作

c++ - 程序如何知道是否需要初始化静态变量?

iOS:当应用程序状态为 UIApplicationStateBackground 时,为什么 dispatch_async 不会运行到主线程?

iphone - 用圆形图像层标记球 - 在 iphone 中触摸缩放或移动

ios - 删除部分时 UITableView 的平滑动画

c++ - 将列表传递到直接初始化时是否使用移动或复制构造函数?

c - 初始化结构指针 - c