C语言 Objective-C NSMutableArray - 具有多个类的对象的 foreach 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3037700/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective-C NSMutableArray - foreach loop with objects of multiple classes
提问by Nils Fischer
I have the NSMutableArray *children in the datastructure-class "Foo" which is the superclass of many others, like "Bar1" and "Bar2". That array stores Bar1 and Bar2 objects to get a tree-like recursive parent-children-structure of subclasses from Foo. To access the objects in the array, I loop through them using the foreach loop in Objective-C:
我在数据结构类“Foo”中有 NSMutableArray *children,它是许多其他类的超类,例如“Bar1”和“Bar2”。该数组存储 Bar1 和 Bar2 对象,以从 Foo 获取子类的树状递归父子结构。为了访问数组中的对象,我使用 Objective-C 中的 foreach 循环遍历它们:
for(Foo *aFoo in children) {
...
}
But often I only need to loop through the objects in the array that have a certain class, in this case I want to perform a task for each object of the class Bar1 in the array children. Using for(Bar1 *anObject in children) again loops through ALL objects and not only the ones with the class Bar1. Is there a way to achieve what I need?
但通常我只需要遍历数组中具有某个类的对象,在这种情况下,我想为数组子项中类 Bar1 的每个对象执行一个任务。再次使用 for(Bar1 *anObject in children) 循环遍历所有对象,而不仅仅是具有类 Bar1 的对象。有没有办法实现我所需要的?
回答by unbeli
You have to loop over all objects and do a type check inside the loop.
您必须遍历所有对象并在循环内进行类型检查。
for(id aFoo in children) {
if ([aFoo isKindOfClass:[Bar1 class]])
...
}
}
回答by Jason Coco
You can do something like this:
你可以这样做:
NSPredicate* bar1Predicate = [NSPredicate predicateWithFormat:@"SELF.class == %@", [Bar1 class]];
NSArray* bar1z = [children filteredArrayUsingPredicate:bar1Predicate];
for(Bar1* bar in children) {
// do something great
}
It's important to note, however, that this won't work with many standard Cocoa classes like NSString, NSNumber, etc. that use class clusters or special implementation classes (e.g., anything that is toll-free bridged with a CoreFoundation type) since the classes won't match exactly. However, this will work with classes you define as long as the class really is an instance of Bar1.
然而,重要的是要注意,这不适用于许多使用类集群或特殊实现类(例如,任何与 CoreFoundation 类型桥接的免费电话)的标准 Cocoa 类,如 NSString、NSNumber 等。类不会完全匹配。但是,这将适用于您定义的类,只要该类确实是 Bar1 的实例。
Emphasis Note: User @Alex suggested that it may not be clear that the classes must match exactly from my note above, so I am restating that. The classes must match exactly for this filter to work, so if you subclass Bar1 or provide some proxy class, you will have to adjust the filter in order for those classes to be included. As written, onlyinstances of Bar1will be returned in the filtered array.
重点说明:用户@Alex 建议可能不清楚这些类是否必须与我上面的说明完全匹配,所以我要重申这一点。这些类必须完全匹配才能使此过滤器工作,因此如果您子类化 Bar1 或提供某些代理类,则必须调整过滤器以包含这些类。由于写的,仅实例Bar1将经滤波的阵列中被返回。

