Lakan Bahande
Lakan Bahande

Reputation: 165

Objective-C: Index Beyond Bounds

I am having a hard time figuring out what error i am really having with my code. It says:

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

Here's the part where the app crashes.

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

Upvotes: 3

Views: 983

Answers (2)

Anoop Vaidya
Anoop Vaidya

Reputation: 46543

Use this way:

Following line is correct 6 values are there in arrTemp.

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

But in this only 3 are going in arrTemp.

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

You are entering in 2nd one....either add more key/values in keyTemp or change your logic.

Upvotes: 0

Anusha Kottiyal
Anusha Kottiyal

Reputation: 3905

Check your code :

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

Upvotes: 2

Related Questions