views:

49

answers:

2

Hi all,

I define protocol with a method name is:

   - (id)initWithDelegate:(id <Foo>)delegate;

While in my project, there also has a third party protocol (in different class):

   - (id)initWithDelegate:(NSObject *)delegate;

In another class, which imports both protocols, I just use the second method:

id thirdPartyObject = [[ThirdPartyClass alloc] initWithDelegate:self];

but XCode display an error: self is not conform <Foo> protocol, while self don't need to conform that protocol.

How to avoid this naming conflict?

+5  A: 

Change the name of the method.

- (id)initWithFooDelegate(id<Foo>)delegate;
Marcus S. Zarra
Actually, I did try this solution, but I still ask if there is other solution for this annoying problem
Thanh-Cong Vo
@Thanh-Cong there's no other solution. In Objective-C, only the name of the method is used to "uniquify" a method. The types of the parameters are not involved. Since a different protocol already defines a method selector of `initWithDelegate:`, you must choose a different name.
Dave DeLong
+4  A: 

I am not 100% sure if I am understanding what you are doing, but I think the problem is that you are trying to use covariant methods in objective C (methods with the same selector name, but differently typed arguments).

Technically speaking the code you have written will work correctly at runtime, but because the compiler does not have enough type information to know what the class o the objective it is dispatching the message to is, it cannot know which of the two different initWithDelegate:'s is the right one for the object, so it guesses (well, I think it actually always uses the first declared one, but the point is that it makes an arbitrary decision). That means that calls to one or the other will always give warnings. Apple's suggested solution is to not use methods with the same name that take different types.

You can checkout this question for some more details.

Louis Gerbarg
Thank for your answer. There has a lot of interesting information
Thanh-Cong Vo