【问题标题】:Is it possible to type check the parameters for an optional protocol method?是否可以键入检查可选协议方法的参数?
【发布时间】:2011-11-08 16:10:12
【问题描述】:

在 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:) 委托是否实现该方法时编译器不会抱怨,它会让我通过 methodDidFail: 消息传递 errorString .相反,稍后在运行时,这将导致无效的选择器崩溃。

如果我想让编译器抱怨并检查参数的类型怎么办?有没有办法做到这一点?

【问题讨论】:

    标签: objective-c ios4 selector


    【解决方案1】:

    不,没有办法检查参数类型。最好在更改类型时添加新方法。我会这样命名委托方法:

    - (void) methodDidFailWithError:(NSError *) error;
    
    - (void) methodDidFailWithString:(NSString *) errorString;
    

    【讨论】:

    • 我认为这是一种可以接受的解决方法,尽管它并不是我所希望的。
    • didFailWithErrorMessage 会更好。
    猜你喜欢
    • 2023-03-23
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 2015-01-23
    • 2015-09-30
    • 2019-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多