zakdances
zakdances

Reputation: 23685

Succinctly evaluating an object with MULTIPLE class checks with isKindOfClass

Is there a better way to see if an object has one of several classes than

if ([item isKindOfClass:[NSArray class]] || [item isKindOfClass:[NSNumber class]] || 
[item isKindOfClass:[NSPredicate class]] || [item isKindOfClass:[NSMutableArray class]] 
|| [item isKindOfClass:[NSString class]]) {
   return YES;
};

Is there a more graceful way than this? Preferably an inline way that doesn't require creating categories or multiline for loops/arrays.

Upvotes: 2

Views: 262

Answers (2)

zakdances
zakdances

Reputation: 23685

Here's what I ended up doing:

NSArray *classes = @[ [NSArray class], [NSDictionary class], [NSSet class] ];
NSUInteger *matches = [classes indexesOfObjectsPassingTest:^BOOL(id class, NSUInteger idx, BOOL *stop) {
           return [item isKindOfClass:class]);
       }].count;

Upvotes: 0

BJ Homer
BJ Homer

Reputation: 49034

Perhaps this?

NSArray *classes = @[ [NSArray class], [NSNumber class], [NSPredicate class], (etc.)];
for (Class cls in classes) {
    if ([item isKindOfClass:cls]) {
        return YES;
    }
}

It's not significantly more succinct, but I think it's easier to read and maintain.

Edit : Naturally, you would add a stipulation about no loops or arrays right as I'm writing this up. :)

You might be able to do it with an NSPredicate and an "@any.FUNCTION(isKindOfClass:)" keypath, but I don't think it would be any more graceful; most people would just find it harder to read. I really think an array and a for loop is the way to go here.

Upvotes: 4

Related Questions