NSSet 使用谓词返回匹配给定类的对象 [英] NSSet use predicate to return objects matching given class
问题描述
假设我有一个 NSSet,它包含一组 id
Let's say I have an NSSet that contains a collection of objects of type id<Shape>
...其中有 CircleShape、SquareShape、HexagonalShape 实例放入其中(不是真正的协议或类名)..
. . . of which there are CircleShape, SquareShape, HexagonalShape instances put into it (not the real protocol or class names) . .
是否可以使用谓词或另一行代码来返回 CircleShape 的所有实例?
is it possible to use a predicate or another single line of code to return all of the instances of CircleShape?
推荐答案
您可以像这样使用基于块的谓词:
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];
这将返回 CircleShape
的所有实例或 CircleShape
的子类.如果您只需要类的实例,而不需要子类的实例,请使用 isMemberOfClass
.
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.
这篇关于NSSet 使用谓词返回匹配给定类的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!