How to find out if an object implements a specific method?

I iterate through NSArray, which contains many different types of objects. There are many ways to find out which class is an object. However, I could not find a good way to find out if an object can implement a specific function. I can put it in a try-catch, but it still gives an error message in the console, even if I catch the error. Is there a better way to do this?

A simple example:

@try { if ([element lowercaseString]) { //do something } } @catch (id theException) { // do something else } 
+7
methods objective-c cocoa
source share
3 answers

As suggested, you can use respondsToSelector: message declared in NSObject . The code provided will look like

 if ([element respondsToSelector:@selector(lowercaseString)]) { // ... do work } 
+22
source share

See how NSObject responds to the Selector method

+5
source share

There is a good category of generic code in code:

 @interface NSObject (KMExtensions) - (id)performSelectorIfResponds:(SEL)aSelector; - (id)performSelectorIfResponds:(SEL)aSelector withObject:(id)anObject; @end @implementation NSObject (KMExtensions) - (id)performSelectorIfResponds:(SEL)aSelector { if ( [self respondsToSelector:aSelector] ) { return [self performSelector:aSelector]; } return NULL; } - (id)performSelectorIfResponds:(SEL)aSelector withObject:(id)anObject { if ( [self respondsToSelector:aSelector] ) { return [self performSelector:aSelector withObject:anObject]; } return NULL; } @end 

And then you can use:

 [element performSelectorIfResponds:@selector(lowercaseString)]; 
+1
source share

All Articles