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开发者_如何学JAVA) 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.
This is pretty easy.
if([delegate respondsToSelector:myOptionalMethod]){
// You can now call this method without a crash
[delegate myOptionalMethod];
}
-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)];
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];
}
精彩评论