超出NSArray的边界异常即为空

时间:2010-11-23 11:37:36

标签: objective-c arrays exception ios4

我有这个代码用于创建要在视图上显示的图像数组。我视图中的大多数页面将有20个图像(5列,4行),但实际上有43个图像,当我的图像数组包含最后3个时,我在内部的第4次迭代时得到异常循环,数组为空。

- (void)displayImages:(NSMutableArray *)images {

NSMutableArray *keysArray = [[NSMutableArray alloc] initWithCapacity:5];

for (int column = 0; column < 5; column++){
    [keysArray  addObject:[NSMutableArray arrayWithCapacity:5]];
    for (int row = 0; row < 4; row++) {
        [[keysArray objectAtIndex:column] addObject:[images objectAtIndex:0]];
        [images removeObjectAtIndex:0];
    }
}

....

我可以解决这个问题吗?

感谢。

编辑:

从这段代码开始,是实际从数组中提取图像的代码。但是同样的情况发生了......在第四次迭代中它崩溃了。

for (int column = 0; column < 5; column++) {
    for (int row = 0; row < 4; row++){          
        UIButton *keyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        keyButton.frame = CGRectMake(column*kKeyGap, row*kKeyGap, kKeySize, kKeySize);

        [keyButton setImage:[[keysArray objectAtIndex:column] objectAtIndex:row] forState:UIControlStateNormal];
        [keyButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:keyButton];
    }
}
[keysArray release];

此时我无法测试images,因为数组已经清空。

3 个答案:

答案 0 :(得分:1)

在尝试对其进行任何操作之前,只需检查该数组中是否有对象

- (void)displayImages:(NSMutableArray *)images { 

NSMutableArray *keysArray = [[NSMutableArray alloc] initWithCapacity:5]; 

for (int column = 0; column < 5; column++){ 
    [keysArray  addObject:[NSMutableArray arrayWithCapacity:5]]; 
    for (int row = 0; row < 4; row++) { 
        //test to see if there's an object left in the inner array
        if ([images count] > 0) {
            [[keysArray objectAtIndex:column] addObject:[images objectAtIndex:0]]; 
            [images removeObjectAtIndex:0];
        }
    } 
} 

答案 1 :(得分:0)

测试images

中的对象数量

答案 2 :(得分:0)

尝试在for循环文本表达式中使用实际的数组大小而不是常量值。所以不是这样:

for (int column = 0; column < 5; column++)

这样做:

for (int column = 0; column < [keysArray count]; column++)

结果代码可能如下所示:

for (int column = 0; column < [keysArray count]; column++) {

    NSArray *rowArray = [keysArray objectAtIndex:column];

    for (int row = 0; row < [rowArray count]; row++) {          
        UIButton *keyButton = [UIButton buttonWithType:UIButtonTypeCustom];
        keyButton.frame = CGRectMake(column*kKeyGap, row*kKeyGap, kKeySize, kKeySize);

        [keyButton setImage:[rowArray objectAtIndex:row] forState:UIControlStateNormal];
        [keyButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];

        [self.view addSubview:keyButton];
    }
}

顺便说一下,嵌套的消息表达式有时很酷,但嵌套调用objectAtIndex:可能永远不是一个好主意。