2

想象一下我有两个协议:

@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>

谢谢!

4

2 回答 2

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;
}
于 2012-04-05T21:29:57.650 回答
0

检查它是否conformsToProtocol(),如果是,然后像这样投射它

myVar = (id <A>)otherVar;

类似的问题可以在Cast an instance to a @protocol in Objective-C 查看

于 2012-04-05T21:26:49.007 回答