是否可以对可选协议方法的参数进行类型检查?
在 iOS4 上,如果我有一个非公共协议,例如:
@protocol HTTPDelegate <NSObject>
@optional
- (void) methodDidFinish:(NSDictionary *) response;
- (void) methodDidFail:(NSString *) error;
@end
并且我有一个指向委托的指针,例如:
id<HTTPDelegate> delegate;
然后,我想选择调用该委托方法:
if( [delegate respondsToSelector:@selector(methodDidFail:)] ) {
[delegate methodDidFail:errorString];
}
这很好用。但是,我后来决定使用 NSError* 来处理错误,并将协议更改为:
@protocol HTTPDelegate <NSObject>
@optional
- (void) methodDidFinish:(NSDictionary *) response;
- (void) methodDidFail:(NSError *) error;
@end
如果我只是更改可选协议方法中一个参数的类型,则当我检查(使用 respondsToSelector:) 如果delegate 实现了该方法,它会让我通过 methodDidFail: 消息传递 errorString。相反,稍后在运行时,这将导致无效的选择器崩溃。
如果我希望编译器抱怨并检查参数的类型怎么办?有办法做到这一点吗?
On iOS4, if I have a non-public protocol like:
@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:
@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. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,没有办法检查参数类型。最好在更改类型时添加新方法。我将委托方法命名为:
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: