error with scrollToRowAtIndexPath

I got this error because I was trying to scroll to row 0 section 0 of an empty tableView. Make sure your tableData.count > 0.


The clean way, assuming self is the tableView datasource:

Check the number of sections in the tableview:

if ( [self numberOfSectionsInTableView:self.tableView]
                                     > oldCheckedIndexPath.section 

and check the number of rows in that section:

  && [self tableView:self.tableView numberOfRowsInSection:
          oldCheckedIndexPath.section] > oldCheckedIndexPath.row )
   {
      [self.tableView scrollToRowAtIndexPath: // etc etc etc

Or, the quick hack:

@try {
    [self.tableView scrollToRowAtIndexPath: // etc etc etc 
}
@catch ( NSException *e )
{
    NSLog(@"bummer: %@",e);
}

Inspired by the accepted answer:

Objective-C:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
if ([self numberOfSectionsInTableView:self.tableView] > indexPath.section && [self tableView:self.tableView numberOfRowsInSection:indexPath.section] > indexPath.row) {
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

Swift:

let indexPath = IndexPath(row: rowToScroll, section: sectionToScroll) 
if (self.tableView.numberOfSections > indexPath.section && self.tableView.numberOfRows(inSection: indexPath.section) > indexPath.row ) {
    self.tableView.scrollToRow(at: IndexPath(row: rowToScroll, section: sectionToScroll), at: .top, animated: true) 
}

I solved it via another option before calling scrollToRowAtIndexPath: this method reload your tableview with [yourtableviewobject reloadData]; and then call:

NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:([messages count] - 1) inSection:0];
[objTableView scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];