Duck
Duck

Reputation: 35943

iPhone - how do I know if a protocol method was implemented?

I have created a class and this class has its own delegate protocol. Inside that protocol, there's an optional method, declared like

@protocol myClassDelegate <NSObject>
@optional
- (void) myOptionalMethod;

@end

Inside the class I have a call to myOptionalMethod, in the form of

[delegate myOptionalMethod];

but as the method is optional, if I call this method on a delegate that has not implemented the method, it will crash.

So, how do I test to see if the method was implemented before calling it?

thanks.

Upvotes: 1

Views: 400

Answers (3)

John Parker
John Parker

Reputation: 54425

You should use the respondsToSelector method to determine if the delegate has the relevant method prior to calling the selector on the delegate.

For example:

if([delegate respondsToSelector:@selector(myOptionalMethod)]) {
    [delegate myOptionalMethod];
}

Upvotes: 2

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

-respondsToSelector: is useful for individual methods, as others have posted here. For a stricter interpretation, you can see whether a class was declared as implementing a protocol with the -conformsToProtocol: method:

BOOL isAGrommet = [myObject conformsToProtocol: @protocol(Grommet)];

Upvotes: 2

John Ballinger
John Ballinger

Reputation: 7540

This is pretty easy.

if([delegate respondsToSelector:myOptionalMethod]){
    // You can now call this method without a crash
    [delegate myOptionalMethod];
}

Upvotes: 2

Related Questions