将第6个元素插入到表格视图中时,为什么会出现NSRangeException?

| 我将数据插入表视图,如下所示。如果5到6个元素超过6个,则App Crashs并显示错误,则没有问题:
\"Terminating app due to uncaught exception \'NSRangeException\', reason: \'*** -[NSMutableArray objectAtIndex:]: index 11 beyond bounds [0 .. 10]\' \"
- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
    return [ProductArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    static NSString *CellIdentifier = @\"Cell\";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) 
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

    }

       NSDictionary *aDict = [ProductArray objectAtIndex:indexPath.row];    
      cell.textLabel.text= [aDict objectForKey:@\"ProductName\"];


    return cell;
}
    
已邀请:
使用此代码
if(indexPath.row < [ProductArray count]){

NSDictionary *aDict = [ProductArray objectAtIndex:indexPath.row];
cell.textLabel.text= [aDict objectForKey:@\"ProductName\"];

}
    
在ѭ3中,必须为oldNumberOfRows + addedRowsNumber行数设置正确的数字。 编辑: 并在ProductArray中添加每行的字典,然后再将行添加到tableview。     
显然,崩溃消息表明您正在尝试访问超出数组可以包含的元素限制的元素。请检查是否要更新表视图和数组中的numberOfRows。     
该错误表明您正在尝试访问仅包含11个对象的NSMutableArray中索引为11(第12个对象)或更高版本的对象。数组索引从0开始,所以可能是问题所在。尝试在ProductArray的大小上执行NSLog并检查其容纳多少个对象。正如许多人在崩溃之前所说的那样,可能是numberofRowsInSection方法。如果您不想打扰ProductArray的大小,只需返回一个固定的数字即可查看其余代码是否正确。     

要回复问题请先登录注册