Search code examples
iosuitableviewnsfetchedresultscontroller

If I have a reference to a UITableViewCell that has to be deleted, how can I delete it from an NSFetchedResultsController?


I've implemented a NSFetchedResultsController, and I've successfully implemented row deletion via the delete button revealed by a swipe (this is the standard control in UITableView, not something custom I've made). Ive done this by overwriting - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath so that the entity in the Core Data database that the cell references is deleted.

Now I want to implement my own deletion control. I've added a UIPanGesture to my UITableViewCell subclass so that when you pan a cell, a delete button is shown that moves in as the cell is swiped out (similar to that in iOS 7 mail app, or Clear app). Via a custom protocol, the view controller that has the NSFetchResultsController recives the cell whose custom delete button has been pressed. With this I can calculate the indexPath by doing NSIndexPath *indexPath = [self.tableView indexPathForCell:cellToDelete]; with the cell that needs to be deleted. Only problem is: How do I delete this cell?

UITableView has a deleteRowsAtIndexPaths: withRowAnimation: method. As far as I can tell, NSFetchResultsController does not have such a method. I guess what I need is somehow for - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath to be called since I've already implemented deletion in there.

Summary: In A UIViewController I have an NSFetchedResultsController and a pointer to a cell (as well as it's indexPath) that needs to be deleted. How do I delete the cell?


Solution

  • The FRC is driven by the contents of your Corw Data model, so, you need to delete the model object associated with the row and the FRC will pick up the change (it is observing the data store) and remove the cell from the table view.