質問

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?

役に立ちましたか?

解決

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

他のヒント

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top