The question is generally coming from self = [super init].
In case if I’m subclassing NSSomething and in my init’s method self = [super init] returns object of different class, does it mean I am not able to have my very own ivars in my subclass, just because self will be pointing to different class?
Appreciate if you could bring some examples if my statement is wrong.
UPD: to make my question more precise.
@implementation Base
-(id) init
{
return [NSNumber numberWithBool:YES];
}
@end
@interface Child : Base
{
int myVeryOwnVar;
}
- (id) init;
- (void) dump;
@end
@implementation Child
- (id) init
{
self = [super init];
myVeryOwnVar = 5;
return self;
}
@end
Child *p = [[Child alloc] init];
[p dump];
This obviously crashed on sending message to p object, since it’s now NSNumber and does not serve dump message. So I lost the control over myVeryOwnVar and in worse cases can have leaks and crashes.
In short, when
[super init]is called, there’s actually a hidden parameter there (self), which is the object set up by your classesalloc. The ivars are already there, but you pass the object that they’re attached to (self) without doing so explicitly.initdoes not set up ivars, but rather initializes them with values.selfis already a valid object pointer when yourinitgets called and[super init]will in almost all cases return either that very sameselfornil.For a more detailed (and probably much more accurate) description see http://cocoawithlove.com/2009/04/what-does-it-mean-when-you-assign-super.html