简体   繁体   English

是否可以键入检查可选协议方法的参数?

[英]Is it possible to type check the parameters for an optional protocol method?

On iOS4, if I have a non-public protocol like: 在iOS4上,如果我有一个非公开协议,例如:

@protocol HTTPDelegate <NSObject>
@optional
- (void) methodDidFinish:(NSDictionary *) response;
- (void) methodDidFail:(NSString *) error;
@end

And I have a pointer to a delegate like: 我有一个指向代理的指针,例如:

id<HTTPDelegate> delegate;

Then, I want to optionally call that delegate method: 然后,我想选择调用该委托方法:

if( [delegate respondsToSelector:@selector(methodDidFail:)] ) {
  [delegate methodDidFail:errorString];
}

That works great. 效果很好。 However, I later decide to use an NSError* for the error and change the protocol to: 但是,我后来决定对错误使用NSError *并将协议更改为:

@protocol HTTPDelegate <NSObject>
@optional
- (void) methodDidFinish:(NSDictionary *) response;
- (void) methodDidFail:(NSError *) error;
@end

If I just change the type of one parameter in an optional protocol method, the compiler won't complain when I check (with respondsToSelector:) if the delegate implements that method and it will let me pass errorString with the methodDidFail: message. 如果我只是在可选协议方法中更改一个参数的类型,则当我检查(使用responsToSelector :)委托是否实现了该方法时,编译器将不会抱怨,它将使我通过methodDidFail:消息传递errorString。 Instead, later, at runtime, this will result in an invalid selector crash. 相反,稍后,在运行时,这将导致无效的选择器崩溃。

What if I want the compiler to complain and check the types of the parameters? 如果我希望编译器抱怨并检查参数类型怎么办? Is there a way to do that? 有没有办法做到这一点?

No there is no way to do check the parameter types. 否,没有办法检查参数类型。 Better you add a new method when you change the types. 最好在更改类型时添加新方法。 I'd name the delegate methods like so: 我会这样命名委托方法:

- (void) methodDidFailWithError:(NSError *) error;

- (void) methodDidFailWithString:(NSString *) errorString;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM