[英]Protocol subclassing and conformance
Given 给定
@protocol Response <NSObject>
@end
@protocol DataResponse <Response>
@end
@interface ListUsersResponse : NSObject <DataResponse>
@end
@interface RequestExecutor : NSObject
+(id<Response>) execute: (id<Request>) request receptor: (Class) model;
@end
ListUsersRequest * request = [self buildListUsersRequest];
ListUsersResponse * result = [RequestExecutor execute:request receptor:[ListUsersResponse class]];
I get an Initializing 'ListUsersResponse *__strong' with an expression of incompatible type 'id<Response>'
error. 我收到
Initializing 'ListUsersResponse *__strong' with an expression of incompatible type 'id<Response>'
错误Initializing 'ListUsersResponse *__strong' with an expression of incompatible type 'id<Response>'
的Initializing 'ListUsersResponse *__strong' with an expression of incompatible type 'id<Response>'
。 Why is that? 这是为什么? Cant the compiler detect protocol conformance?
无法让编译器检测协议一致性? How to solve it?
怎么解决呢?
These warning is because your RequestExecutor
's execute:
method returns an object of a general id<Response>
type. 这些警告是因为您的
RequestExecutor
的execute:
方法返回的是常规id<Response>
类型的对象。 The variables, however, are declared as ListUsersResponse *
so the compiler expects a more specific type (and it isn't sure if that type cast is correct or not, it has no way of knowing). 但是,这些变量被声明为
ListUsersResponse *
因此编译器期望使用更特定的类型(并且不确定该类型ListUsersResponse *
是否正确,无法知道)。
You can get rid of the warning by either: 您可以通过以下两种方法消除警告:
a) Declaring your variables with id<Response>
type instead of ListUsersRequest *
type like: a)用
id<Response>
类型而不是ListUsersRequest *
类型声明变量:
id<Response> result = [RequestExecutor execute:request receptor:[ListUsersResponse class]];
Or 要么
b) Casting them on the fly (if you are sure that at that point they will be of the appropriate class): b)即时投放它们(如果您确定到那时它们将属于适当的班级):
ListUsersResponse *result = (ListUsersRequest *)[RequestExecutor execute:request receptor:[ListUsersResponse class]];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.