Checking to see if an optional protocol method has been implemented

IphoneObjective CDelegatesProtocols

Iphone Problem Overview


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!

Iphone Solutions


Solution 1 - Iphone

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

@protocol MyProtocol <NSObject>

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

@end

Solution 2 - Iphone

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNick CartwrightView Question on Stackoverflow
Solution 1 - IphoneWill HarrisView Answer on Stackoverflow
Solution 2 - IphoneJavier Calatrava LlaveríaView Answer on Stackoverflow