Question

First of all, by filtering, means finding all the (targetClass) views in the subviews.

Normally, if we want to filter subviews by class, we probably do:

// Create an array to hold them
NSMutableArray *filteredViews = [NSMutableArray new];

// enumerate and check
for (UIView *view in parentView.subviews) {
    if ([view isMemberOfClass:[targetClass class]) {
        [filteredViews addObject:view];
    }
}   

Is this the proper way to do it?

Does Cocoa Touch have a dedicated method to filter subviews?

Was it helpful?

Solution

You can use NSPredicate to define a rule to select the items you want. Note I'm using isKindOfClass, and not isMemberOfClass, since the former takes class hierarchy into account, and will be able to identify subclasses of the class you are looking for.

NSPredicate* predicate = [NSPredicate predicateWithFormat:@"self isKindOfClass: %@", [targetClass class]];
NSArray* filteredViews= [parentView.subviews filteredArrayUsingPredicate:predicate];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top