Christian
Christian

Reputation: 1975

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

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?

Upvotes: 1

Views: 230

Answers (1)

Felix
Felix

Reputation: 35384

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;

Upvotes: 1

Related Questions