views:

267

answers:

3

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
}
+5  A: 

Look at NSObject's respondsToSelector method

drvdijk
+17  A: 

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

if ([element respondsToSelector:@selector(lowercaseString)]) {
    // ... do work
}
notnoop
+1 for best answer with link and code example.
Quinn Taylor
Don't forget that the colons are an inseparable part of the selector. @selector(catFish) is completely different from @selector(catFish:).
Chuck
+1  A: 

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)];
Peter N Lewis