infernouk infernouk - 7 days ago 6
Swift Question

Issues with core data persisting when making changes to entities

I have features to delete and edit my core data entities via the UI. Although the changes work in the UI, they are not persisted when returning to the view. I am sure I have missed something thats causing no save to take place, but cant figure it out. Is it just a case of adding the standard save throw and catch to the end of the delete function? As that gives me unwrapping errors unless ? or ! are used

I have included the switch case for the functions an example:

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {
switch (type) {
case .insert:
if let indexPath = newIndexPath {
workoutDesignerTable.insertRows(at: [indexPath], with: .fade)
}
break;
case .delete:
if let indexPath = indexPath {
workoutDesignerTable.deleteRows(at: [indexPath], with: .fade)
}
break;
case .update:
if let indexPath = indexPath, let cell = workoutDesignerTable.cellForRow(at: indexPath) as? RoutineTableViewCell {
configure(cell, at: indexPath)
}
break;
default:
print("...")
}
}


the delete func

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Fetch Exercise
let UserExercise = fetchedResultsController.object(at: indexPath)
// Delete Exercise
UserExercise.managedObjectContext?.delete(UserExercise)
}
}

Answer

I think you need something like this

            func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
            if editingStyle == .delete {
                let UserExercise = fetchedResultsController.managedObjectContext
                UserExercise.delete(fetchedResultsController.object(at: indexPath))
                do {
                    try UserExercise.save()
                } catch {
                    // Replace this implementation with code to handle the error appropriately.
                    // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                    let nserror = error as NSError
                    fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
                }
            }
        }