Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a method exists

Tags:

objective-c

People also ask

How do you check if a method exists for a class?

Use the typeof operator to check if a method exists in a class, e.g. if (typeof myInstance. myMethod === 'function') {} . The typeof operator returns a string that indicates the type of the specific value and will return function if the method exists in the class.

How do you check if a function is defined in PHP?

The function_exists() is an inbuilt function in PHP. The function_exists() function is useful in case if we want to check whether a function() exists or not in the PHP script. It is used to check for both built-in functions as well as user-defined functions.


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

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).


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.


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.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!