想象一下,我有两个协议:
@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>
谢谢!
答案 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
查看类似的问题