NSRange Exception

UITableView scrollToRowAtIndexPath problem

出现的提示是这样的: Terminating app due to uncaught exception 'NSRangeException', reason: '-[UITableView scrollToRowAtIndexPath:atScrollPosition:animated:]: section (0) beyond bounds (0).'
- (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"]; }
解决办法:

Reload TableView data before calling scrollToRowAtIndexPath.

[contentTableView reloadData];



NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; if (indexPath != nil) {     [EventTable scrollToRowAtIndexPath:indexPath                 atScrollPosition:UITableViewScrollPositionTop animated:YES]; }

 if (([EventTable numberOfSections] > 0) && ([EventTable numberOfRowsInSection: 0] > 0)) 
{
 [EventTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
 }
增加一个判断,预防程序崩掉。 Before scrolling to an IndexPath, check your UITableView to make sure the row and section you're trying to scroll to are less than the number of rows and section in your table, respectively. If so, do not try to scroll to that IndexPath.

你可能感兴趣的:(exception,table,less,scroll)