Reputation: 721
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;
}
Upvotes: 2
Views: 199
Reputation: 28572
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.
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.
This is described in Implementing an Initializer.
Upvotes: 3