Pablo
Pablo

Reputation: 29519

Subclassing Cocoa means no subclass ivars in some cases?

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.

Upvotes: 0

Views: 290

Answers (2)

Nick Moore
Nick Moore

Reputation: 15857

The self = [super init] will not return an object of different class, although it can return an instance of the class that differs from the calling instance. However, it will always be of class NSSomething, or a subclass of NSSomething, and you are always able to have your own instance variables.

Upvotes: 1

Joonas Trussmann
Joonas Trussmann

Reputation: 1064

In short, when [super init] is called, there's actually a hidden parameter there (self), which is the object set up by your classes alloc. The ivars are already there, but you pass the object that they're attached to (self) without doing so explicitly. init does not set up ivars, but rather initializes them with values.

self is already a valid object pointer when your init gets called and [super init] will in almost all cases return either that very same self or nil.

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

Upvotes: 1

Related Questions