[英]Protocol subclassing and conformance
给定
@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]];
我收到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>'
。 这是为什么? 无法让编译器检测协议一致性? 怎么解决呢?
这些警告是因为您的RequestExecutor
的execute:
方法返回的是常规id<Response>
类型的对象。 但是,这些变量被声明为ListUsersResponse *
因此编译器期望使用更特定的类型(并且不确定该类型ListUsersResponse *
是否正确,无法知道)。
您可以通过以下两种方法消除警告:
a)用id<Response>
类型而不是ListUsersRequest *
类型声明变量:
id<Response> result = [RequestExecutor execute:request receptor:[ListUsersResponse class]];
要么
b)即时投放它们(如果您确定到那时它们将属于适当的班级):
ListUsersResponse *result = (ListUsersRequest *)[RequestExecutor execute:request receptor:[ListUsersResponse class]];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.