简体   繁体   English

具有协议继承的objc不兼容指针类型

[英]objc incompatible pointer type with protocol inheritance

I am running with Xcode version 5.1, iOS SDK version 7.1. 我正在使用Xcode版本5.1,iOS SDK版本7.1运行。 Here are some sample declarations all in the same file: 以下是一些声明声明,它们都在同一文件中:

@protocol A <NSObject>
@end

@protocol B <A>
@end

@interface SomeObject : NSObject <B>
@end

@interface SomeContainer : NSObject
- (id<A>)pop;
@end

Xcode generates a warning in the following code: Xcode在以下代码中生成警告:

SomeContainer *container = [[SomeContainer alloc] init];
SomeObject *obj = [container pop]; // Warning: Initializing 'SomeObject *__strong' with and expression of incompatible type 'id<A>'

I know that typecasting will get rid of the warning, however, I don't understand why I need it. 我知道类型转换将摆脱警告,但是,我不明白为什么需要它。 SomeObject must implement whatever is declared in protocol A. Is there something that I am missing? SomeObject必须实现协议A中声明的任何内容。我缺少什么吗? Any explanation would be greatly appreciated. 任何解释将不胜感激。

Probably this is because SomeObject is something more than just id<A> . 可能是因为SomeObject不仅仅是id<A> It's like initialising an object of derived class with pointer to the base class. 就像使用指向基类的指针初始化派生类的对象一样。 You can initialize an instance of id<A> with SomeObject but when you do it vice versa you're receiving a warning, which says :"Hey, buddy you've just assigned base to derived, ie something that is present in derived (SomeObject *) may be missed in base id<A> " 您可以使用SomeObject初始化id<A>的实例,但是反之亦然,您会收到一条警告,提示:“嘿,伙计,您刚刚将基数分配给派生对象,即派生对象(SomeObject *)基本id<A>可能缺少(SomeObject *)

for example SomeObject may contain method foo which is not present in protocol A , but now after that assignment of yours if you send foo message to obj it may crash, because id<A> is not necessarily has this method. 例如, SomeObject可能包含协议A不存在的方法foo ,但是在您的赋值之后,如果您向obj发送foo消息,则它可能会崩溃,因为id<A>不一定具有此方法。 It can, if it's also an instance of SomeObject , but it can be anything, which NECESSARILY responds only to the methods declared in A . 如果它也是SomeObject的实例,也可以,但是可以是任何东西,它仅对A声明的方法作出响应。

I hope all this makes sense 我希望所有这些都有意义

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM