views:

72

answers:

2

I know I can do

for (id obj in array)
{
    if ([obj isKindOfClass:[Elephant class]])
        [elephants addObject:obj];
}

but I feel there must be a more elegant way of doing this. I've looked at filtering arrays but can't come up with a good predicate. Thoughts?

+3  A: 

The predicate would be something like

Class ec = [Elephant class];
NSPredicate *elePred = [NSPredicate predicateWithFormat:@"class==%@", ec];
NSArray *elephants = [array filteredArrayUsingPredicate:elePred];

or

NSPredicate *elePred = [NSPredicate predicateWithFormat:@"self isKindOfClass: %@", ec];

I have found predicates to be quite, er.. shall we say "Heavy". I would probably prefer your code to this.

If you are just looking to spice up your life a little you could use blocks to add a little concurrency…

    NSMutableArray *results = [NSMutableArray array];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop){
        if([obj isKindOfClass:[Elephant class]])
            [results addObject:obj];
    }];
mustISignUp
A: 

You can create category to NSMutableArray and add next method:

- (void)addObject:(id)anObject ifItIsKindOfClass:(Class) classObj {
    if ([anObject isKindOfClass:classObj]) {
        [self addObject:anObject];
    }
}

And simple write:

for (id obj in array)
{
        [elephants addObject:obj ifItIsKindOfClass:[Elephant class]];
}

There is one plus: reusable.

Skie
I put it in a C function. There's no need for it to be an instance member of the array class, or even a static member. Adding it to NSMutableArray seems senseless, as it works just as well for other types of array.
Ranking Stackingblocks