UITableView
我有一个由 an 管理的相当香草NSFetchedResultsController
来显示给定核心数据实体的所有实例。
当用户通过滑动删除表格视图中的条目时,tableView:cellForRowAtIndexPath:
最终会在 myUITableViewController
上调用nil
indexPath
. 因为我没想到它会被调用nil
indexPath
,所以应用程序崩溃了。
nil
我可以通过检查该值然后返回一个空单元格来解决崩溃问题。这似乎可行,但我仍然担心我可能处理了错误的事情。有任何想法吗?有没有人见过tableView:cellForRowAtIndexPath:
用 a 打电话的nil
indexPath
?
请注意,这只发生在用户通过滑动单元格从表格视图中删除时。使用表格视图编辑模式删除项目时,不会发生。两种删除单元格的方法有什么不同?
nil
indexPath
那么在表格视图中获得委托方法真的是一种好的情况吗?
我的视图控制器代码非常标准。这是删除:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
[self.moc deleteObject:managedObject];
NSError *error = NULL;
Boolean success = [self.moc save:&error];
if (!success) { <snip> }
// actual row deletion from table view will be handle from Fetched Result Controller delegate
// [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else { <snip> }
}
这将导致NSFetchedResultsController
调用委托方法:
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeInsert: <snip> break;
case NSFetchedResultsChangeUpdate: <snip> break;
case NSFetchedResultsChangeMove: <snip> break;
}
}
当然,数据源方法由 处理NSFetchedResultsController
,例如:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
非常感谢。