我已经在解决这个问题上取得了一些进展,基本上是通过忽略numberOfObjects
并返回我希望表格固定的实际长度。这需要一些技巧,controller:didChangeObject:...
但到目前为止似乎有效。
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return kTableSize;
//return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.myTableView;
switch(type) {
case NSFetchedResultsChangeInsert:
// Only modify table if insert will effect visible rows
if (newIndexPath.row < kTableSize) {
// Delete last row to maintain fixed length
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:(kTableSize - 1) inSection:newIndexPath.section]] withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
break;
case NSFetchedResultsChangeDelete:
// Only modify table if delete will effect visible rows
if (indexPath.row < kTableSize) {
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
// Insert extra row to maintain fixed length
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:(kTableSize - 1) inSection:newIndexPath.section]] withRowAnimation:UITableViewRowAnimationAutomatic];
}
break;
case NSFetchedResultsChangeUpdate:
// Only modify table if update will effect visible rows
if (indexPath.row < kTableSize) {
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
break;
case NSFetchedResultsChangeMove:
// Only modify table if move will effect visible rows
if ((indexPath.row < kTableSize) || (newIndexPath.row < kTableSize)) {
// Delete old row or last row of table
if (indexPath.row < kTableSize) {
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
} else {
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:(kTableSize - 1) inSection:newIndexPath.section]] withRowAnimation:UITableViewRowAnimationAutomatic];
}
// Insert new row or a row at bottom of table
if (newIndexPath.row < kTableSize) {
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
} else {
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:(kTableSize - 1) inSection:newIndexPath.section]] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
break;
}
}
如果对象少于表长度,还需要注意tableView:cellForRowAtIndexPath:
确保我们不会尝试访问不存在的对象。