Reputation: 63
When we do self = [super init];
in our subclass's init method implementation,
I don't understand why it's not self= [[super alloc] init];
In the first case, how can you init something that you haven't allocate memory for?
Is this because you're not actually initing a superclass object but instead using the superclass's init method to init yourself first?
If so, where and when did we allocate memory for self?
Is it just assumed that we did the alloc somewhere else in our program before calling this init method?
Is the syntax basically saying [subclass initUsingMySuperClassImplementationFirst]
?
Upvotes: 3
Views: 759
Reputation: 66302
I don't understand why it's not
self= [[super alloc] init];
Because when init
is called, someone else has already allocated memory.
Note that alloc
is a class method, and init
is an instance method. When init
is called, the object has already been created.
For example:
MyObject *someObject = [[MyObject alloc] init];
alloc
creates and returns an allocated MyObject
. init
just sets things up - initializes any custom properties, etc.
This is equivalent to:
MyObject *someObject = [MyObject alloc];
someObject = [someObject init];
Is it just assumed that we did the alloc somewhere else in our program before calling this init method?
It's not just assumed, it's guaranteed - because it's impossible to get to init
without doing so. For example, if you called:
MyObject *someObject = [MyObject init];
This wouldn't work, because init
is an instance method, not a class method. (See What is the difference between class and instance methods? if you want to read more about the difference.)
Upvotes: 9
Reputation: 2874
The reason is because by the time your subclass's init
method has been called, memory has already been allocated for it. You don't need to allocate memory for the superclass, as you are not instantiating it - you are calling the superclass's init
method which already exists. There is a difference between allocation and instantiation.
This is the same paradigm as in other languages like Java. alloc
is a class method, not an instance method, so the only way init
can ever be called is if alloc
has been called already.
Actually, calling [[super alloc] init]
would likely produce an unnecessary leaked object, as you have allocated memory that will go out of scope at the end of init
, which is a bad thing.
Upvotes: 0