简体   繁体   English

当我要求我的表视图滚动到顶部时,为什么会出现NSRangeException?

[英]Why am I getting an NSRangeException when asking my table view to scroll to top?

I am using a subclassed tableView made by someone else and it comes with a method loadObjects that causes the tableView to repopulate its cells, however it doesn't tell the table view to return to the top after the repopulation. 我正在使用由其他人创建的子类tableView,它附带了一个方法loadObjects ,它导致tableView重新填充其单元格,但是它不会告诉表视图在重新填充后返回到顶部。 I tried to implement this feature with: 我尝试用以下方法实现此功能:

- (void)loadObjects{
    [super loadObjects];
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

However once loadObjects is called (when the table view wants to initially load), i get the following exception: 但是一旦loadObjects (当表视图想要初始加载时),我会得到以下异常:

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

I transferred the line I wrote that scrolls the table view to the top to another custom method that is called whenever I pressed a button, and it worked totally fine, so there is a problem in my overwriting of loadObjects . 我将我写的用于滚动表视图的行转移到另一个自定义方法,每当我按下一个按钮时调用它,并且它完全正常,因此我覆盖loadObjects出现问题。 Does anyone understand the exception that was thrown? 有人理解抛出的异常吗?

在调用scrollToRowAtIndexPath之前测试重新加载tableview。

[self.tableView reloadData];

As some of the commenters pointed out, you'll see this error when attempting to scroll to an index path that does not exist (according to the results of numberOfSectionsInTableView and numberOfRowsInSection). 正如一些评论者指出的那样,当您尝试滚动到不存在的索引路径时(根据numberOfSectionsInTableView和numberOfRowsInSection的结果),您将看到此错误。

So the fix is to not attempt to scroll to a non-existent index path. 所以修复是不要尝试滚动到不存在的索引路径。 You might achieve this fix by changing the order in which this method is called, relative to loading your data (as the commenters suggested), or by some other means (eg changing the way you compute which index path to scroll to, or only scrolling conditionally if the index path is sure to exist). 您可以通过更改调用此方法的顺序,相对于加载数据(如评论者建议的),或通过其他方式(例如,更改计算滚动到的索引路径的方式,或仅滚动)来实现此修复有条件地,如果索引路径肯定存在)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM