我需要在用户滚动时动态更新tableview。我正在显示来自大型数据库的数据,因此为了内存管理,我使用以下代码在用户滚动时动态更新表。我所做的是当tableView加载indexPath.row == 30
并且用户向下滚动并从头开始删除30行时,我通过在表的末尾添加30行来更新tableView。类似地,当indexPath.row == 20
和用户向上滚动时,30行被添加到开头,30行开始从末尾删除。以下条件写在tableView:cellForRowAtIndexPath
if ((indexPath.row == 30) && isDown) {
[self addRowsToBeginningOfTable];
}
if ((indexPath.row == 20) && isUp) {
[self addRowsToEndOfTable];
}
在此,当用户滚动时isDown为true,当用户向下滚动时isUp为true(我知道它很奇怪,但isUp和isDown是来自用户的滑动方向)。 addRowsToBeginningOfTable
和addRowsToEndOfTable
如下:
- (void)addRowsToEndOfTable {
NSInteger rowCount = [arrayOfText count];
int rowId = [[arrayOfText objectAtIndex:rowCount-1]intValue];
for (int i = 0; i < 30; i++) {
NSIndexPath *indexPathEnd = [NSIndexPath indexPathForRow:i+rowCount inSection:0];
NSIndexPath *indexPathBeginning = [NSIndexPath indexPathForRow:i inSection:0];
[tableView beginUpdates];
[arrayOfText insertObject:@"New Object" atIndex:--rowId];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPathEnd] withRowAnimation:UITableViewRowAnimationNone];
[arrayOfText removeObjectAtIndex:i];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPathBeginning] withRowAnimation:UITableViewRowAnimationNone];
[tableView endUpdates]; //exception breakpoint hits here
}
}
- (void)addRowsToBeginningOfTable {
NSInteger rowCount = [arrayOfText count];
int rowId = [[arrayOfText objectAtIndex:0]intValue];
for (int i = 0; i < 30; i++) {
NSIndexPath *indexPathEnd = [NSIndexPath indexPathForRow:i+rowCount inSection:0];
NSIndexPath *indexPathBeginning = [NSIndexPath indexPathForRow:i inSection:0];
[tableView beginUpdates];
[arrayOfText addObjectAtIndex:i WithRowId:--rowId];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPathBeginning] withRowAnimation:UITableViewRowAnimationNone];
[arrayOfText removeObjectAtIndex:i+rowCount];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPathEnd] withRowAnimation:UITableViewRowAnimationNone];
[tableView endUpdates];
}
}
但是当我滚动tableView并且indexPath.row == 30
条件满足时,应用程序崩溃显示以下错误:
*** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /SourceCache/UIKit_Sim/UIKit-2372/UITableView.m:909
我设置了一个异常断点,并看到它在上面代码中给出了注释的行。我怎么能纠正这个?或者这不是更新表的正确方法,而用户不知道在滚动时是否正在更新tableView?