Check if a method exists

Objective C

Objective C Problem Overview


Is there any way I can test if a method exists in Objective-C?

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

Objective C Solutions


Solution 1 - Objective C

if ([obj respondsToSelector:@selector(methodName:withEtc:)]) {
   [obj methodName:123 withEtc:456];
}

Solution 2 - Objective C

There is also the static message instancesRespondToSelector:(SEL)selector You would call it like this:

[MyClass instancesRespondToSelector:@selector(someMethod:withParams:)]

or like this:

[[myObject class] instancesRespondToSelector:@selector(someMethod:withParams:)]

This may be useful if you would like to call one constructor or another one depending on this (I mean, before having the instance itself).

Solution 3 - Objective C

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.

Solution 4 - Objective C

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.

Solution 5 - Objective C

Checking selectors with respondsToSelector is normally only for delegate methods. You shouldn't be using forwardInvocation or proxies for delegate methods. If you need to use respondsToSelector in other situations you might want to make sure that there isn't a more appropriate way to design your program.

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
QuestionteepusinkView Question on Stackoverflow
Solution 1 - Objective CkennytmView Answer on Stackoverflow
Solution 2 - Objective CRicard Pérez del CampoView Answer on Stackoverflow
Solution 3 - Objective CCarl NorumView Answer on Stackoverflow
Solution 4 - Objective CFrank SheararView Answer on Stackoverflow
Solution 5 - Objective CEricView Answer on Stackoverflow