NSSet 使用谓词返回匹配给定类的对象 [英] NSSet use predicate to return objects matching given class

查看:70
本文介绍了NSSet 使用谓词返回匹配给定类的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆