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) ?

4

1 回答 1

3

1)它会在if条件下进行赋值。

2)设置myInstanceVariable时,self 已经指向新对象,因为if条件中的赋值首先完成。实际上,如果 if条件中的赋值不成功,则永远不会处理myInstanceVariable赋值。

顺便提一句。据我所知,所有对myInstanceVariable的直接调用都解析为:

无论如何,self->myInstanceVariable 。

编辑:只是为了解决你在评论中的问题,看看这个答案: https ://stackoverflow.com/a/1341801/703809

于 2013-09-05T13:56:06.317 回答