Problem with self = [super init];


#1

Hello, I have a problem with the “Implementation of the designated initializer” on page 51, the problem is explained in the next page but I just can’t understand it.
self = [super init];
I don’t understand what that line of code does.
Can anyone help me?
Thanks!


#2

[quote]self = [super init];
I don’t understand what that line of code does.
Can anyone help me? [/quote]
That line of code does two things:

  1. Asks the superclass part of the object to initialise itself. (As part of its initialisation, the superclass part may return a different object.)
  2. Makes sure that self becomes the same object returned by [super init] statement.

Point 2 is important to understand. Because [super init] statement may return a different object than the original one in self, that assignment to self is crucial.

@implementation Foo
...
- (instancetype)initWithBar:(Bar *)bar
{
     // Save the original object
     NSObject * originalFoo = self;

     // Here self == originalFoo
     self = [super init];
     // But here, because [super init] may return a different object, it is not always that self == originalFoo
      ...
     return self;
}
...
@end

Therefore, it is unorthodox to write an init function, without assigning to self:

@implementation Foo
...
- (instancetype)initWithBar:(Bar *)bar
{
     [super init];
     ...
     return self;
}
...
@end

[Become a competent programmer: pretty-function.org]