Incompatible Objective-C types initializing struct

This bizarre iPhone compiler error message had me tearing my hair out this morning. I’ve finally figured it out.

Here’s the scene: You have two classes, each class has an init method with the same name and taking the same parameters. Here’s an example:

@interface myClass1 : NSObject { }

-(myClass1 *)initWithName:(NSString *)name;


@interface myClass2 : NSObject { }

-(myClass2 *)initWithName:(NSString *)name;


Now try to initialize an instance of the first class:

myClass1 *c = [[myClass1 alloc] initWithName:@"Fred"];

You get Incompatible Objective-C types initializing ‘struct myClass2 *’, expected ‘struct myClass1 *’ which doesn’t make any sense because the initializer never even mentions myClass2.

The thing is that the program will run fine, it just gives this warning at compile-time because the compiler can’t tell the difference between two different methods with the same signature. I like my code to compile with no errors and no warnings because I’m very fussy. So even though this warning could be safely ignored, it still bugs me and I have to get rid of it!

So to shut the compiler up, I need to cast the object so it explicitly knows which method to call.

myClass1 *c = [(myClass1 *)[myClass1 alloc] initWithName:@"Fred"];

Casting always looks ugly to me but that’s the way around it.