Objective-C:指数超越界限

时间:2012-12-19 06:47:00

标签: objective-c ios nsarray

我很难弄清楚我的代码到底有什么错误。 它说:

reason: '*** -[__NSArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 2]'

以下是应用崩溃的部分。

NSString *keyTemp = [[NSString alloc] initWithFormat:@"Wit%d",indexPath.section+1];
    NSArray *arrTemp;
    if ([userStandards objectForKey:keyTemp] == nil || [[userStandards objectForKey:keyTemp] count]==3) {
        if ([witDict objectForKey:keyTemp] == nil) {
            arrTemp = [[NSArray alloc] initWithObjects:@"",@"",@"",@"",@"",@"",nil];
        } else {
            arrTemp = [[NSArray alloc] initWithArray:[witDict objectForKey:keyTemp]];
        }
        cell.inputTextArea.text = [NSString stringWithFormat:@"Name: %@\nPhone: %@\nEmail: %@\nCity/State: %@\nZip: %@\nComments: %@",[arrTemp objectAtIndex:0],[arrTemp objectAtIndex:1],[arrTemp objectAtIndex:2], [arrTemp objectAtIndex:3], [arrTemp objectAtIndex:4], [arrTemp objectAtIndex:5]];
    } else {
        arrTemp = [[NSArray alloc] initWithArray:[userStandards objectForKey:keyTemp]];
        cell.inputTextArea.text = [NSString stringWithFormat:@"Name: %@\nPhone: %@\nEmail: %@\nCity/State: %@\nZip: %@\nComments: %@",[arrTemp objectAtIndex:0],[arrTemp objectAtIndex:1],[arrTemp objectAtIndex:2], [arrTemp objectAtIndex:3], [arrTemp objectAtIndex:4], [arrTemp objectAtIndex:5]];
}

2 个答案:

答案 0 :(得分:2)

检查您的代码:

if ([[userStandards objectForKey:keyTemp] count]==3)
{

  // Your array only have 3 elements (index 0,1, and 2)

  // Here you accessing index beyond 2
  cell.inputTextArea.text = [NSString stringWithFormat:@"Name: %@\nPhone: %@\nEmail: %@\nCity/State: %@\nZip: %@\nComments: %@",[arrTemp objectAtIndex:0],[arrTemp objectAtIndex:1],[arrTemp objectAtIndex:2], [arrTemp objectAtIndex:3], [arrTemp objectAtIndex:4], [arrTemp objectAtIndex:5]];
}

答案 1 :(得分:0)

使用这种方式:

以下行是正确的arrTemp中有6个值。

arrTemp = [[NSArray alloc] initWithObjects:@"",@"",@"",@"",@"",@"",nil];

但是在这个中只有3个进入arrTemp。

arrTemp = [[NSArray alloc] initWithArray:[witDict objectForKey:keyTemp]];

你正在进入第二个......要么在keyTemp中添加更多的键/值,要么改变你的逻辑。

相关问题