Object initialization sequence in Objective-C

Posted by Alex on Stack Overflow See other posts from Stack Overflow or by Alex
Published on 2011-01-15T12:52:10Z Indexed on 2011/01/15 12:53 UTC
Read the original article Hit count: 121

Filed under:
|

Hello everyone.

The Cocoa framework has a convention to always call self = [super init] in the init method of an inherited class, because [super init] may return a new instance.

What will happen if I do this?

@interface MyClass : NSObject /* or any other class */ {
    int ivar_;
}
@end

@implementation MyClass

- (id)init {
    ivar_ = 12345;

    if ((self = [super init])) {
        NSLog(@"ivar_'s value is %d", ivar_);
    }
    return self;
}

@end

In the case when [super init] returns a new instance, what will I see in the console? ivar_'s value is 0?

I can't think of a way to check this myself, because I don't know which class may return a new instance from its init method. Also, can't seem to find explicit clarification for this scenario in the docs.

Could anyone help me out? Thanks!

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about init