55

Does anyone know the best way to check to see if an optional protocol method has been implemented.

I tried this:

if ([self.delegate respondsToSelector:@selector(optionalProtocolMethod:)] )

where delegate is:

id<MyProtocol> delegate;

However, I get an error saying that the function respondsToSelector: is not found in the protocol!

Bobrovsky
  • 13,789
  • 19
  • 80
  • 130
Nick Cartwright
  • 8,334
  • 15
  • 45
  • 56

2 Answers2

101

respondsToSelector: is part of the NSObject protocol. Including NSObject in MyProtocol should solve your problem:

@protocol MyProtocol <NSObject>

@optional
-(void)optionalProtocolMethod:(id)anObject;

@end
Will Harris
  • 21,597
  • 12
  • 64
  • 64
5

What I do is applying the following recipe:

if(self.delegate && [self.delegate respondsToSelector:@selector(closed)]){
    [self.delegate closed];
}

Where 'closed' is the method that I wanted to call.

  • Does that a overkill? If delegate doesn't exist. [self.delegate respondsToSelector:@selector(closed)] will return nil. – Alex Aug 25 '20 at 16:58