Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find out if an object implements a particular method?

I am iterating through an NSArray that contains many different types of objects. There are many methods to figure out what class the object is. However, I haven't been able to find a good way to find out if an object can implement a particular function. I can put it in a try-catch but it will still output an error message in the console even if I'm catching the error. Is there a better way to do this?

Simple example:

@try {
    if ([element lowercaseString]) {
        //do something
    }
}
@catch (id theException) {
    // do something else
}
like image 736
Jason Avatar asked Jul 09 '09 13:07

Jason


1 Answers

As suggested, you can use respondsToSelector: message declared on NSObject. The provided code would be like

if ([element respondsToSelector:@selector(lowercaseString)]) {
    // ... do work
}
like image 56
notnoop Avatar answered Nov 05 '22 20:11

notnoop