NSSet use predicate to return objects matching given class

一曲冷凌霜 提交于 2019-12-05 22:17:34

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/14276018/nsset-use-predicate-to-return-objects-matching-given-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!