NSSet use predicate to return objects matching given class
Asked Answered
S

1

7

Let's say I have an NSSet that contains a collection of objects of type id<Shape>

. . . of which there are CircleShape, SquareShape, HexagonalShape instances put into it (not the real protocol or class names) . .

is it possible to use a predicate or another single line of code to return all of the instances of CircleShape?

Surprising answered 11/1, 2013 at 10:20 Comment(0)
O
12

You can use a block-based predicate like this:

NSSet *yourSet = ...;
NSPredicate *pred = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
    return [evaluatedObject isKindOfClass:[CircleShape class]];
}];
NSSet *filteredSet = [yourSet filteredSetUsingPredicate:pred];

This would return all instances of CircleShape or subclasses of CircleShape. Use isMemberOfClass if you want only instances of the class, but not of subclasses.

Otic answered 11/1, 2013 at 10:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.