Jason
Jason

Reputation: 17956

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
}

Upvotes: 7

Views: 1508

Answers (3)

notnoop
notnoop

Reputation: 59299

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

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

Upvotes: 22

Peter N Lewis
Peter N Lewis

Reputation: 17811

A nice generic category to have in your code is this:

@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)];

Upvotes: 1

drvdijk
drvdijk

Reputation: 5554

Look at NSObject's respondsToSelector method

Upvotes: 5

Related Questions