NSSet uses a predicate to return objects matching this class

Say I have an NSSet that contains a collection of objects of type id <Shape>

., of which it includes instances of CircleShape, SquareShape, HexagonalShape (and not the real names of the protocols or classes).,

Can I use a predicate or other line of code to return all instances of CircleShape?

+7
source share
1 answer

You can use a block-based predicate as follows:

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

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

+11
source

All Articles