tags:

views:

46

answers:

2

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.

+1  A: 

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.

invariant
Class cluster init methods do not necessarily return instances of the superclasshttp://developer.apple.com/mac/library/documentation/cocoa/reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/uid/20000154-397865
JeremyP
@Joonas Trussmann, @invariant: updated original post.
Michael
@JeremyP: thanks for attending my question, really hope to see your answer as well ^^
Michael
@JeremyP I edited the answer to indicate that it could be a subclass too
invariant
+1  A: 

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

Joonas Trussmann
I kind of missed the part where you specified the case of [super init] returning an instance of a different object. The right information to head towards would be "As with any class cluster, if you create a subclass of NSNumber, you have to override the primitive methods of its superclass, NSValue." but I'm afraid this is a bit beyond me to explain.
Joonas Trussmann