2010-05-19 123 views
6

在我的应用程序中,我尝试在更新表格的内容后将UITableView滚动到顶部。但是,在某些情况下,我的表格是EMPTY。所以,我得到了以下异常:iphone dev - 如何捕捉异常'NSRangeException'

终止应用程序由于未捕获的异常 'NSRangeException',原因是:“ - [UITableView的scrollToRowAtIndexPath:atScrollPosition:动画:]:行(0)超出范围(0)的部分(0 )“。

我该怎么捕捉这个异常?我试过

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0]; 

if (indexPath != nil) { 
    [EventTable scrollToRowAtIndexPath:indexPath 
       atScrollPosition:UITableViewScrollPositionTop animated:YES]; 
} 

但它没有捕获异常,因为indexPath不是零。

回答

12

在滚动到IndexPath之前,请检查您的UITableView,以确保您尝试滚动的行和部分分别小于表中的行数和部分数量。如果是这样,请不要尝试滚动到该IndexPath。

if ([tableView numberOfSections] < section || [tableView numberOfRowsInSection] < row) 
+0

谢谢。我就是这样做的。 如果((事件表numberOfSections]> 0)&&([事件表numberOfRowsInSection:0]> 0)){ \t \t [事件表scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0切入口:0] atScrollPosition:UITableViewScrollPositionTop动画:YES]; \t} – Brian 2010-05-20 17:28:07

+1

&&将是正确的,而不是||。 ? – 2010-10-13 13:59:02

+0

@ S.P,这取决于您是否测试是否滚动,或测试是否中止。 – 2014-12-16 08:48:47

6

异常处理采用与典型流控制表达式不同的路径。苹果已经写了一篇关于Objective-C Exception Handling的有用文章。本质上,您需要将代码包装在@try/@catch区块中。它位于@catch块中,您将收到异常并在您的代码中执行相应的后续步骤。

+1

@ try/@ catch的作品,但我总是尽量避免使用它。我认为最好是避免发生异常,而不是在发生异常时抓住它)=)但是,谢谢 – Brian 2010-05-20 17:30:11

+6

同意 - 你的问题是特别要求如何捕捉异常,而不是如何避免异常;我正在为你回答这个问题。 – fbrereto 2010-05-20 17:31:50

+1

文章链接已变:http://developer.apple.com/library/mac/#documentation/cocoa/conceptual/objectivec/Chapters/ocExceptionHandling.html#//apple_ref/doc/uid/TP30001163-CH13-SW1 – bearMountain 2012-01-04 00:19:23