1

In ObjectiveC, recommended idiom of an init method is :

- (id)init {
    if (self = [super init]) {
        myInstanceVariable = someConstant;
    }
    return self;
}

This is because, superClass's init might return a different object than the current object, freeing the current object using [self release];

If that happens :

1) After the call to [super init] finishes, won't control return to original object's init method ?

2) And, won't the next line set myInstanceVariable of the original object ( on which, super-class called release) ?

And if this is the case, would changing the line to :

self->myInstanceVariable = someConstant;

help (so that, myInstanceVariable of the object returned by [super init] is set, instead of the original object) ?

Hitesh Gupta
  • 333
  • 1
  • 3
  • 8

1 Answers1

3

1) It will, to do the assignment in the if condition.

2) By the time the myInstanceVariable is set, self already points to the new object, because the assignment in the if condition is done first. In fact the myInstanceVariable assignment is never processed if the assignment in the if condition is not successful.

Btw. as far as I can tell, all the direct calls to myInstanceVariable are resolved to:

self->myInstanceVariable anyway.

EDIT: Just to address your question in the comments, take a look at this answer: https://stackoverflow.com/a/1341801/703809

Community
  • 1
  • 1
lawicko
  • 7,246
  • 3
  • 37
  • 49
  • 2
    Yes, `self->ivar` and `ivar` are exactly the same. A reference to `ivar` has an implicit `self->` attached to it. – rmaddy Sep 05 '13 at 14:03
  • From what I understood, self is just like any other local variable, it is a hidden parameter which is set to the object receiving the message at the runtime by the method invoking function. Hence, didn't think ivar would resolve to self->ivar automatically. If it does, that means, we should never be assigning arbitrary values to self. – Hitesh Gupta Sep 05 '13 at 14:08
  • He's already answered similar question here: http://stackoverflow.com/a/1289199/703809 – lawicko Sep 05 '13 at 14:15