0

我想了解如何在 2D 中使用 for-each 语句NSMutableArray。我的代码如下。它在第三个(最里面的)for 语句引发异常。例外是:

"Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber count]: unrecognized selector sent to instance"

我的代码:

NSMutableArray* subTryingSet=[NSMutableArray arrayWithArray:[self genSetNumbers:arrRandoms withSize:4]];

for (NSMutableArray* oneRow in subTryingSet) {
    for (NSMutableArray* w in oneRow) {
        for (int i=0;i<w.count;i++) {
            NSLog(@"%d", [[w objectAtIndex:i] intValue]);
        }
    }
}
4

2 回答 2

3

在第一次快速查看您的代码之后:

尝试改变这一点:

    NSLog(@"%d", [[w objectAtIndex:i] intValue]);

和:

   NSLog(@"%i", [[w objectAtIndex:i] intValue]);

编辑

“它在第 3 个“for 语句”抛出异常,所以它不能去 slog”

嗯……你确定 oneRow 中的所有对象都是 NSMutableArray 吗?

尝试像这样检查:

for (NSMutableArray* oneRow in subTryingSet) {
  if ([oneRow.class isSubclassOfClass:[NSMutableArray class]]) {
      for (NSMutableArray* w in oneRow) {
        if ([w.class isSubclassOfClass:[NSMutableArray class]]) {
            for (int i=0;i<w.count;i++) {
                NSLog(@"%d", [[w objectAtIndex:i] intValue]);
            }
        }
      }
  }
}
于 2012-04-13T09:45:16.050 回答
0

您可以使用此自定义目标 c 方法进行迭代

-(void)loopMultArray:(NSArray*)a walk:(void(^)(id node,int index,int zindex))n{

    void(^callback)(id node,int index,int zindex) = Block_copy(n);

    NSMutableArray *l=[[[NSMutableArray alloc] initWithObjects:a,nil] autorelease];
    int c=1;
    //This first loop will loop until the count var is stable//
    for(int r=0;r<c;r++){
        //This loop will loop thru the child element list//
        for(int z=0;z<[[l objectAtIndex:r] count];z++){

            callback([[l objectAtIndex:r] objectAtIndex:z],z,r);

            if([[[l objectAtIndex:r] objectAtIndex:z] isKindOfClass:[NSArray class]]){
                [l addObject:[[l objectAtIndex:r] objectAtIndex:z]];
                c++;
            }//IF
        }//FOR
    }//FOR

    Block_release(callback);

}
于 2014-09-13T17:24:10.023 回答