Search code examples
iphoneuitableviewios5custom-cell

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?


Solution

  • 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] : @"";
    }