Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking to see if an optional protocol method has been implemented

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!

like image 270
Nick Cartwright Avatar asked Feb 04 '09 17:02

Nick Cartwright


2 Answers

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

@protocol MyProtocol <NSObject>

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

@end
like image 77
Will Harris Avatar answered Oct 19 '22 20:10

Will Harris


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.

like image 23
Javier Calatrava Llavería Avatar answered Oct 19 '22 19:10

Javier Calatrava Llavería