[英]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.