views:

330

answers:

2

I have a class 'DOInstance' which I inherit later on. Here's its declaration:

@interface DOInstance : NSObject {

}

- (DOInstance *) initWithSynckey:(NSString *)_synckey;
@end

Then I have a subclass of DOInstance:

@interface Workflow_Workitem_Header_1px: DOInstance {

}
//- (Workflow_Workitem_Header_1px *) initWithSynckey:(NSString *)_synckey;
@end

I go ahead and implement it in the implementation file:

- (Workflow_Workitem_Header_1px *) initWithSynckey:(NSString *)_synckey {

    [super initWithSynckey:_synckey];
    //..
    //..
    return self;
}

Now, If I do not declare initWithSynckey: (the commented declaration above) in my subclass declaration, I get a warning at the implementation: "warning: initialization from distinct Objective-C type". If I declare it, this warning goes away. Okay.

Moving on:

I later do an instantiation of my subclass:

Workflow_Workitem_Header_1px *instance;
instance = [[Workflow_Workitem_Header_1px alloc] initWithSynckey:@"xxxx"];

Now, this gives me the same warning (irrespective of whether or not I declare the corresponding initWithSynckey: selector in my subclass. Namely, "warning: initialization from distinct Objective-C type".

What am I doing wrong?

+1  A: 

Methods named init... should have return type (id), not the type of the class. Check out NSString.h and NSArray.h (among other classes) for examples. That may be what is causing your problem.

corprew
Yes, that was in fact the problem. I did not know this until now. Thanks!
submachine
A: 

In this case, the overriding method must return the same type as the superclass' declaration.

DOInstance defines this:

- (DOInstance *) initWithSynckey:(NSString *)_synckey;

so Workflow_Workitem_Header_1px must look like this:

@interface Workflow_Workitem_Header_1px: DOInstance {
}
- (DOInstance *) initWithSynckey:(NSString *)_synckey;
@end

Any time you get the warning "warning: initialization from distinct Objective-C type" you're doing something in contravention of your typing: changing a method signature, and the like.

Frank Shearar
I was under the impression that it will not be a problem because the overridden method returns a subclass of type used by the original definition. I corrected it by having every level return (id) just like most of the NS* classes.
submachine
You're still returning an Objective-C instance and, because Objective-C is late-bound, as long as you're sending messages that the receiver understands, everything will still work.The warning's there to tell you that you're monkeying with how you declared types, and the compiler's not prepared to _guarantee_ that things will work. Objective-C has _optional_ manifest typing.You don't, in fact, need any type info at all: -foo { return [[NSString alloc] init] } is a perfectly acceptable method. (Well, "no type information" means "everything's an id".)
Frank Shearar