alloc
allocates a chunk of memory to hold the object, and returns the pointer.
MyClass*myObj=[MyClass alloc];
myObj
cannot be used yet, because its internal state is not correctly set up. So, don't write a code like this.
init
sets up the initial condition of the object and returns it. Note that what's returned by [a init]
might be different from a
. That explains the code Yannick wrote:
-init{
self=[super init]; // 1.
if(self){ // 2.
....
}
return self; // 3.
}
- First, you need to call the superclass's
init
, to set up the superclass's instance variables, etc. That might return something not equal to the original self
, so you need to assign what's returned to self
.
- If
self
is non-nil, it means the part controlled by the superclass is correctly initialized. Now you perform your initialization. All of the instance variables are set to nil
(if it's object) and 0
if it's integer. You'll need to perform additional initial settings.
- Return the set-up
self
. The returned self
might be different from what's allocated! So, you need to assign the result of init
to your variable.
This gives us an important lesson: never split the call to alloc
and init
. Don't do
MyClass*myObj = [MyClass alloc];
[myObj init];
because [myObj init]
might return something else. Don't do
MyClass*myObj = [MyClass alloc];
myObj=[myObj init];
because you will eventually forget to write the part myObj=
in the second line.
Always do
MyClass*myObj = [[MyClass alloc] init];
I don't recommend
MyClass*myObj = [MyClass new];
either, because it does not correctly call the initialization method: some class doesn't accept a plain init
. For example, NSView
needs initWithFrame:
, which can't be called with new
. So, don't use new
.