views:

42

answers:

1

Why would the following code throw this error?

if ([self.tableView.dataSource numberOfSectionsInTableView:self.tableView] > 0 && [self.tableView.dataSource tableView:self.tableView numberOfRowsInSection:0] > 1) {
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
}

throws

* Terminating app due to uncaught exception 'NSRangeException', reason: '-[UITableView scrollToRowAtIndexPath:atScrollPosition:animated:]: section (0) beyond bounds (0).'

It's pretty early in the morning, but I'm stumped.

+1  A: 

Try to call [self.tableView reloadData] just before the lines that you post.

I bet that the datasource is ready after the table is rendered and you call the scrollTo... method before rendering the table with the data in the datasource...

Michael Kessler
That may be correct, but it seems unacceptable to me since the table will then reload twice on view loading. It sounds like what I really need is a callback to my delegate like "tableDidReload". A tableview calls reloadData on itself automatically when a view is created, so when does that happen? It seems like it should happen before viewDidAppear is called, but that doesn't seem to be the case.
DougW
I don't see all your code, but I am sure that you may put the code that you've posted after the `reloadData`. I am pretty sure that you use `reloadData` after you fill the datasource...
Michael Kessler