tags:

views:

41

answers:

2

I have a method like this which performs further initializations on other objects with similar init methods.

- (Foo*)initWithInput:(NSMutableString*)i {
  bar = [[Bar alloc] initWithInput:input];
  return self;
}

This produces a warning "Foo.m:19: warning: incompatible Objective-C types assigning 'struct Foo *', expected 'struct Bar *'"

I am assuming the alloc method is returning an (id) type and then the compiler can't decide which initWithInput: method I want to use on the allocated object. I can of course remove the warning like this but it's not terribly pretty

- (Foo*)initWithInput:(NSMutableString*)i {
  bar = [((Bar*)[Bar alloc]) initWithInput:input];
  return self;
}

Is there an idiomatic way of handling this?

+5  A: 

Is there an idiomatic way of handling this?

Objective-C has a flat namespace for selectors and does not support covariant dispatch (a la Java and C++). Thus, you need to name your methods uniquely per argumentation.

This is also the standard pattern of the frameworks. You [generally -- there are 1 or 2 exceptions] don't see two methods with the same name -- the same selector -- with different argumentation. When it does happen -- like the return value of alloc -- you'll see id used.

bbum
Inside cocoa there are a couple of cases where there are combined alloc-init methods like stringWithFormat:. I have tried making my own version of these but it didn't turn out very well for some reason I don't remember right now.
Björn Skoglund
@Björn: Those are a bit different, see [Class Factory Methods](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW36).
Georg Fritzsche
+1  A: 

All init-methods should return id and not the type of the class they belong to for exactly this reason. This is actually documented by Apple somewhere. I can’t find the link at the moment, though.

Sven
Sort of; an -init* method will return a specific type if it is never supposed to be subclassed. There are a very small number of methods that do exactly that in the system frameworks, mostly deprecated for exactly the reason you state, though.
bbum