The application currently supports creating, reading, and updating notes. But it should also be possible to delete notes. The pieces we need to add the ability to delete notes are already present in the notes view controller. In fact, we only need to implement one additional method of the UITableViewDataSource protocol to add support for deleting notes.
Deleting a Note
Open NotesViewController.swift and revisit the implementation of the UITableViewDataSource protocol. The method we need to implement is tableView(_:commit:forRowAt:).
NotesViewController.swift
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
}
We exit early if the value of editingStyle isn't equal to delete.
NotesViewController.swift
guard editingStyle == .delete else { return }
We then fetch the note that corresponds with the value of the indexPath parameter.
NotesViewController.swift
// Fetch Note
guard let note = notes?[indexPath.row] else { fatalError("Unexpected Index Path") }
To delete the managed object, we pass the note to the delete(_:) method of the managed object context to which the note belongs.
NotesViewController.swift
// Delete Note
note.managedObjectContext?.delete(note)
The implementation also works if we use the managed object context of the Core Data manager because it's the same managed object context.
NotesViewController.swift
// Delete Note
coreDataManager.managedObjectContext.delete(note)
Build and Run
Run the application and delete a note to make sure everything is working as expected.
In the next few episodes, we refactor the notes view controller. Instead of manually keeping track of the notes of the persistent store, we outsource this to an instance of the NSFetchedResultsController class, another useful component of the Core Data framework.