1

假设我有一个带有类方法的基类:

@interface 基础:NSObject

+(id)方法;

@结尾

而且我有10个派生类:从派生1到派生10,每个类都覆盖方法:

@interface derived1 : base 
@end

现在这就是问题所在,我有一个这样的数组:

NSArray *array = [NSArray arrayWithObjects:[derived1 class],[derived2 class].......[derived10 class]];

现在我想遍历这个数组并调用每个元素的方法,怎么做?

PS:我需要在foreach循环中一一执行该方法。

4

3 回答 3

2
  1. 像往常一样迭代
  2. 获取对象的类
  3. 调用该方法

    for (id object in objects) {
        [[object class] method];
    }
    

编辑

以上是如果您有具体实例(@Alladinian :) 欢呼),否则如果您的示例代码是文字并且您实际上将类放在您刚刚使用的数组中

for (id object in objects) {
   [object method];
}
于 2012-08-10T10:36:21.093 回答
1

Given that you have an array like the one you posted:

NSArray *array = [NSArray arrayWithObjects:[derived1 class],[derived2 class]..[derived10 class]];

[array makeObjectsPerformSelector:@selector(method)];

EDIT: OP edited the question and said that he needs to iterate and execute one by one. So go with Paul's answer, it's really what you need :)

于 2012-08-10T10:38:23.603 回答
0

Look up NSArray methods. makeObjectsPerformSelector or makeObjectsPerformSelector:withObject: or enumerateObjectsUsingBlock: or enumerateObjectsWithOptions:usingBlock: all do that. Plus you could simply iterate with a for and call the method on each object.

于 2012-08-10T10:43:50.633 回答