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
performFetch
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()
})
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.