【发布时间】:2013-07-20 10:24:20
【问题描述】:
当我的 UITableView 为空时,我正在尝试放置一个自定义的空单元格。
我使用以下代码:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int count = [self.fetchedResultsController fetchedObjects].count;
if (count == 0) {
return 1;
}
return count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell * cell = nil;
int count = [self.fetchedResultsController fetchedObjects].count;
if (count == 0) {
// return empty cell
cell = [self getEmptyCellOfTableView:tableView cellForRowAtIndexPath:indexPath];
} else {
cell = [self getMyQuestionCellOfTableView:tableView cellForRowAtIndexPath:indexPath];
}
return cell;
}
FRC didChangeObject 实现:
- (void)controller:(NSFetchedResultsController *)controller
didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath
forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
if (!self.suspendAutomaticTrackingOfChangesInManagedObjectContext)
{
switch(type)
{
case NSFetchedResultsChangeInsert:
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeMove:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
}
这很好用,问题是当 fetchedObject.count > 0 比我得到以下错误:
CoreData: error: Serious application error.
An exception was caught from the delegate of NSFetchedResultsController during a call to -
controllerDidChangeContent: Invalid update: invalid number of rows in section 0.
The number of rows contained in an existing section after the update (1)
must be equal to the number of rows contained in that section before the update (1),
plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted)
and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).
with userInfo (null)
我知道发生这种情况是因为我插入了 1 个新行并且计数保持在 1 而不是变为 2。
我该如何解决它以适应我的行为?
【问题讨论】:
-
显示您的 FRC 委托方法实现。更改为
[tableView reloadData]进行快速修复。 -
@Wain 您能否举例说明在何处更改为
[tableView reloadData]以及您希望我展示哪些 FRC 方法? -
@Danpe:每个更改都必须致电
reloadData,这样您就不会再收到任何动画更新。我认为这就是为什么 Wain 称其为“快速修复”的原因。 - 如我的回答所示,应该可以通过适当的动画表格视图更新来解决这个问题。
标签: ios objective-c core-data uitableview