NSArray错误:NSCFArray objectAtIndex索引(5)超出边界(5)

时间:2012-06-06 08:57:37

标签: ios objective-c crash runtime-error

我有一个填充了数据库中值的MutableArray:

NSMutableArray *objectsArray = [[NSMutableArray alloc] init];
for (int n=0; n<[self.array count]; n++) {
    [objectsArray addObject:[[self.array objectAtIndex:n] objectForKey:@"Name"]];
    [objectsArray addObject:[[self.array objectAtIndex:n] objectForKey:@"Name_En"]];
}

我在标签上显示的值如下:

cell.textLabel.text = [[[dic objectForKey:@"d"] objectAtIndex:indexPath.row] objectForKey:@"Name"];
cell.detailTextLabel.text = [[[dic objectForKey:@"d"] objectAtIndex:indexPath.row] objectForKey:@"Name_En"];

到目前为止该应用程序运行良好。它在没有抛出异常的情况下启动,值在标签中。但是,如果我开始滚动应用程序崩溃,我会收到以下错误:

Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (5) beyond bounds (5)'

为什么会出现此错误?

3 个答案:

答案 0 :(得分:1)

你可能会说你有6行的表,但实际上有5个。这个例外的原因是表视图要求indexPath.row的单元格值为5,这意味着它认为有6 [0:5]行,但字典中的数组有5个项[0:5]。

答案 1 :(得分:0)

我面临着你之前提到过的问题。 然后我这样做了: -

cell.TitleLabel.text=[[AllUserDataArray objectAtIndex:indexPath.row]objectAtIndex:0];
cell.DateAndTimeLabel.text=[[AllUserDataArray objectAtIndex:indexPath.row]objectAtIndex:1];
cell.InfoLabel.text=[[AllUserDataArray objectAtIndex:indexPath.row]objectAtIndex:2];
if([[AllUserDataArray objectAtIndex:indexPath.row] count] >3) {

 NSData *imageData=[[AllUserDataArray objectAtIndex:indexPath.row]objectAtIndex:3];
 UIImage *travelImage=[UIImage imageWithData:imageData];
 cell.ImgView.image=travelImage;

它工作正常,逻辑上也正确(我想是这样):)

希望这会对你有所帮助。

答案 2 :(得分:0)

我遇到了同样的问题,我得到了解决方案:

NSMutableArray * objectsArray = [[NSMutableArray alloc] init];

objectsArray=nil;

for (int n=0; n<[self.array count]; n++) {
    [objectsArray addObject:[[self.array objectAtIndex:n] objectForKey:@"Name"]];
    [objectsArray addObject:[[self.array objectAtIndex:n] objectForKey:@"Name_En"]];
}