tags:

views:

140

answers:

4

Hi, is there anyway I can test if a method exist in Objective-C?

I'm trying to add a guard to see if my object has the method before calling it.

Thanks,
Tee

+7  A: 
if ([obj respondsToSelector:@selector(methodName:withEtc:)]) {
   [obj methodName:123 withEtc:456];
}
KennyTM
+1  A: 

Use respondsToSelector:. From the documentation:

respondsToSelector:

Returns a Boolean value that indicates whether the receiver implements or inherits a method that can respond to a specified message.

- (BOOL)respondsToSelector:(SEL)aSelector

Parameters
aSelector - A selector that identifies a message.

Return Value
YES if the receiver implements or inherits a method that can respond to aSelector, otherwise NO.

Carl Norum
+4  A: 

You're looking for respondsToSelector:-

if ([foo respondsToSelector: @selector(bar)] {
  [foo bar];
}

As Donal says the above tells you that foo can definitely handle receiving the bar selector. However, if foo's a proxy that forwards bar to some underlying object that will receive the bar message, then respondsToSelector: will tell you NO, even though the message will be forwarded to an object that responds to bar.

Frank Shearar
A: 

There's also the question of whether this is the right approach in the first place, since Objective-C classes can respond to selectors that they haven't declared (via - forwardInvocation:).

Donal Fellows