alloc/init 以及实例变量的设置
据我了解,除了分配内存之外,alloc
还将所有实例变量(除了isa
变量)设置为零或为零的等效类型,例如 nil
、NULL
和 0.0。
但我最近阅读了以下有关 init 的内容:
初始化设置实例 对象的变量合理 和有用的初始值。
我对“合理且有用的初始值”的含义有点困惑......
如果 alloc
已将值设置为零,则 init
是否会更改这些值以任何方式?
It is my understanding that, in addition to allocating memory, alloc
sets all instance variables (with the exception of the isa
variable) to zero or to the equivalent type for zero, such as nil
, NULL
, and 0.0.
But I recently read the following about init:
Initialization sets the instance
variables of an object to reasonable
and useful initial values.
I'm a bit confused as to what "reasonable and useful initial values" means....
If alloc
has already set the values to zero, is init
altering these values in any way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当然。
例如,您可能有一个表示矩形的对象,其中 ivar 表示宽度和高度;在
init
中,您可以将这些 ivars 初始化为一些合理的默认值,例如 300x200。这就是他们所谈论的一切。
如果您询问 NSObject 的
-init
方法是否将子类的 ivars 的值初始化为某些非零值,答案当然是否定的。Sure.
For example, you may have an object that represents a rectangle with ivars to represent width and height; in
init
you may initialize these ivars to some sane default, say 300x200.That's all they're talking about.
If you're asking whether NSObject's
-init
method is initializing the values of your subclass's ivars to some non-zero values, the answer of course is no.是的,这是完全可能的。例如,数据结构可能具有需要分配和初始化动态内存的成员变量。
alloc
调用将为成员变量保留空间,init
调用将使这些值变得有用(例如,子分配和初始化)。alloc
和init
是分开的,因为一个类可以有多个init
例程,它们以不同的方式初始化对象。您还可以通过调用
new
同时调用alloc
和init
。因此以下两行是等效的:Yes, it is entirely possible. For example, a data structure may have member variables that require dynamic memory be allocated and initialized as well. The
alloc
call will reserve the space for the member variables and theinit
call will make those values useful (e.g., suballocation & initialization).alloc
andinit
are separate because you can have multipleinit
routines for a class that initialize an object in differing ways.You can also call
alloc
andinit
at the same time by callingnew
. Thus the following two lines are equivalent: