Checking to see if an optional protocol method has been implemented

Nick Cartwright picture Nick Cartwright · Feb 4, 2009 · Viewed 15.8k times · Source

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!

Answer

Will Harris picture Will Harris · Feb 4, 2009

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

@protocol MyProtocol <NSObject>

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

@end