Geowil Geowil - 1 year ago 108
iOS Question

didSelectRowAtIndexPath returns out of bounds index

Whenever I have enough items loaded into my UITableView that I can scroll down far enough to move items off of the screen the didSelectRowAtIndexPath method code I have implemented spits out an invalid index value which crashes my app.

Here is my method code, pretty standard fair:

- (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath{
UITableViewCell *cell = [self.tableView.visibleCells objectAtIndex:indexPath.row];
selImg = cell.imageView.image;

[self next];

As an example, if the tableView has 15 rows from data entered into the data source only 12 will show at any one time on the screen. According to the tableView those elements at 0-11. If I scroll down to the other three rows and select one the tableView is still showing that it has elements 0-11 but the indexPath says that row 14 was selected.

This throws the following NSRangeException:

'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index
14 beyond bounds [0 .. 11]'

Searched on Google and SO a bit and could not find an issue similar to mine and I don't really know how to correct this issue as this code, or something similar, seems to be the standard way to get the index value of a selected row.

Answer Source

Try to modify your code

UITableViewCell *cell = [self.tableView.visibleCells objectAtIndex:indexPath.row];


UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download