出界的NSArray例外那空(Out of Bounds Exception on NSArray

2019-10-29 13:30发布

我有用于创建图像的阵列上显示的视图此代码。 大多数在我看来,网页将有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作为阵列已经清空在这一点上。

Answer 1:

尝试使用实际的数组的大小,而不是常数值在你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:可能不是一个好主意。



Answer 2:

只是检查,看看是否有数组中的对象,你尝试用它做任何事情之前

- (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];
        }
    } 
} 


Answer 3:

测试对象在数字images



文章来源: Out of Bounds Exception on NSArray thats Empty