An elegant way to get all objects of a certain type in an Objective-C array

I know what I can do

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

but I feel that there should be a more elegant way to do this. I looked at filtering arrays but could not find a good predicate. Thoughts?

+3
source share
2 answers

The predicate will 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 found that the predicates are pretty, uh ... we say "heavy." I would prefer your code.

If you just want to enliven your life a bit, you can use blocks to add a bit of concurrency ...

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

You can create a category before NSMutableArrayand add the following method:

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

And a simple entry:

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

: .

0

Source: https://habr.com/ru/post/1742465/


All Articles