views:

783

answers:

2

I'm trying to make my table view remember it's last position, so that after the app is run again, it will scroll to that position. to do this, in my viewWillDisappear: method, I get the first visible row number and save it to NSUserDefaults. then in my viewDidAppear I try to scroll to that row by sending scrollToRowAtIndexPath to the table view. However I get a NSRangeException:

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

any help appreciated. Here is the code:

- (void)viewDidAppear:(BOOL)animated
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];

    if ([userDefaults valueForKey:@"content_row"] != nil)
    {
     int rowToHighlight = [[userDefaults valueForKey:@"content_row"] intValue];
     NSIndexPath * ndxPath= [NSIndexPath indexPathForRow:rowToHighlight inSection:0];
     [contentTableView scrollToRowAtIndexPath:ndxPath atScrollPosition:UITableViewScrollPositionTop  animated:YES];
    }
}

-(void) viewWillDisappear:(BOOL)animated
{
    NSIndexPath *selectedRowPath = [[contentTableView indexPathsForVisibleRows] objectAtIndex:0];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setInteger:selectedRowPath.row forKey:@"content_row"];
}
+1  A: 

It's possible that the contentTableView has not yet finished loading the data.

DyingCactus
How do I get notified when it is finished?
Ali Shafai
Sorry, I thought the scrollToRowAtIndexPath was being called in viewDidLoad. I have similar calls in viewDidAppear but instead of returning to a saved row number, I return to a saved key value which is saved in didSelectRowAtIndexPath. Before calling scrollToRowAtIndexPath, I find that key value's row in the currently loaded data source.
DyingCactus
A: 

Reload TableView data before calling scrollToRowAtIndexPath.

[contentTableView reloadData];

William Rust