Object initialization sequence in Objective-C
- by Alex
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!