为什么输入id <someprotocol>的变量不能接收id <otherprotocol>的参数,即使'otherProtocol'符合'someProtocol'?</otherprotocol> </someprotocol>

时间:2012-04-05 21:22:21

标签: objective-c ios macos polymorphism protocols

想象一下,我有两个协议:

@protocol A
@end

@protocol B <A> // Protocol B conforms to protocol A.
@end

还有两个变量:

id<A> myVar = nil;

id<B> otherVar = //correctly initialized to some class that conforms to <B>;

那么,为什么我不能将'otherVar'分配给'myVar'?

myVar = otherVar; //Warning, sending id<B> to parameter of incompatible type id<A>

谢谢!

2 个答案:

答案 0 :(得分:1)

协议的(B)声明(不仅仅是它的前向声明)是否可见?声明是否在myVar = otherVar;之前?

当声明顺序正确时,clang没有抱怨。

举例说明:

@protocol A
@end

@protocol B; // << forward B

void fn() {
    id<A> myVar = nil;
    id<B> otherVar = nil;
    myVar = otherVar; // << warning
}

// declaration follows use, or is not visible:    
@protocol B <A>
@end

而正确订购的版本不会产生警告:

@protocol A
@end

@protocol B <A>
@end

void fn() {
    id<A> myVar = nil;
    id<B> otherVar = nil;
    myVar = otherVar;
}

答案 1 :(得分:0)

检查它是否为conformsToProtocol(),如果是,则将其投射为

myVar = (id <A>)otherVar;

可以在Cast an instance of a class to a @protocol in Objective-C

查看类似的问题