Shaan Singh Shaan Singh - 4 months ago 12
Swift Question

Core Data: Inserting a new row after performing fetch

I'm having trouble figuring out this GCD problem.

Let's say there's one UITableViewCell in the table view. This cell has some text fields that the user is editing. After the user finishes editing, the cell creates a new object in Core Data based on what the user typed in. This object is inserted with

insertNewObjectForEntityForName
.

After this, I need to
performFetch
on the NSFetchedResultsController and reload the tableview. However, I also want to add a new cell to the end of the tableview, so the user can add another item to their list.

This is what I'm doing to try that:

dispatch_async(dispatch_get_main_queue(), {
do {
try self.fetchedResultsController.performFetch()
} catch {
fatalError("Fetch failed: \(error)")
}

self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.fetchedResultsController.sections!.first!.numberOfObjects - 1, inSection: 0)], withRowAnimation: .Automatic)
self.tableView.reloadData()
})


The new cell is added, but without the row animation. I think there's something I'm misunderstanding with GCD and Core Data. Thanks for the help.

Answer

Fixed this by implementing:

func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?)

Using a switch statement inside of this function allows for more control over each change that occurs:

switch type {
    case NSFetchedResultsChangeType.Insert:
        print("Insert")
    case NSFetchedResultsChangeType.Delete:
        print("Delete")
    case NSFetchedResultsChangeType.Update:
        print("Update")
    case NSFetchedResultsChangeType.Move:
        print("Move")
}

Inside this switch, you can use the indexPath to remove cells, add cells, whatever you want. Just use insertRowsAtIndexPaths or another relevant function.

Comments