Shaan Singh Shaan Singh - 1 year ago 80
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


After this, I need to
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)

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 Source

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:
    case NSFetchedResultsChangeType.Delete:
    case NSFetchedResultsChangeType.Update:
    case NSFetchedResultsChangeType.Move:

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download