el.severo
el.severo

Reputation: 2277

indexPath.row throws an exception

I'm toggling the datasource of an tableview but the indexPath.row throws me an exception [index x beyond bounds]

cell.customLabel.text = [[(_secondTab.selected) ? secondArray : firstArray objectAtIndex:indexPath.row]elementName];

Any idea how to solve this?

Upvotes: 1

Views: 505

Answers (2)

KingofBliss
KingofBliss

Reputation: 15115

This may occur when the index value is out of range. Make sure that secondArray and firstArray has same number of values. Or else use your logic to verify that it is out of range or not?

For example, if the datasource is secondArray, your indexPath.row is 4

firstArray has 3 values, secondArray has 6 values. In that situation [firstArray objectAtIndex:4] will throw an exception.

Upvotes: 1

Andrew
Andrew

Reputation: 7720

The problem is that the index indexPath.row is larger than what exists in either secondArray or firstArray. To fix the root cause, you need to figure out why the element is missing from your arrays. To ensure it doesn't crash and simply loads an empty string in the label's text property, check that the largest index in the array is greater than or equal to indexPath.row:

if (_secondTab.selected) { 
    cell.customLabel.text = (indexPath.row <= ([secondArray count]-1)) ? [[secondArray objectAtIndex:indexPath.row] elementName] : @"";
} else {
    cell.customLabel.text = (indexPath.row <= ([firstArray count]-1)) ? [[firstArray objectAtIndex:indexPath.row] elementName] : @"";
}

Upvotes: 1

Related Questions