开发者

objc: avoid protocol method name conflicts?

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?


Change the name of the method.

- (id)initWithFooDelegate(id<Foo>)delegate;


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜