init方法模式 [英] init method pattern
问题描述
我在理解这是什么/如何工作时遇到了问题。似乎很奇怪指定self从init消息返回
I am having problems understanding what/how this works. it seems odd assigning self to return from the init message
- (id)init
{
if((self=[super init])) {
//code here for setting up
}
return self;
}
推荐答案
init
方法首先分配隐式 self
局部变量( self
是两者中的一个传递给方法的隐藏参数)到超类的指定初始化程序的返回值。这背后的原因是初始化器可以返回与接收消息的对象不同的对象,例如,当无法正确初始化接收器或返回现有实例以避免初始化新实例时。
The init
method first assigns the implicit self
local variable (self
is one of the two hidden arguments passed to methods) to the return value of the superclass's designated initializer. The reason behind this is that initializers can return a different object than the one that received the message, for example, when it is not possible to initialize the receiver correctly or when an existing instance is returned to avoid the need to initialize a new one.
设置 self
后, if
语句确保如果 self
不是 nil
,则仅初始化实例变量。如果 self
是 nil
,则访问实例变量的内存可能是错误的。很少有类返回 nil
但仍然是有效的返回值。
After self
is set, the if
statement ensures that instance variables are only initialized if self
is not nil
. If self
is nil
, accessing the memory for the instance variables may be an error. Very few classes return nil
but still it is a valid return value.
这在实施初始化程序。
这篇关于init方法模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!