remove existing record from coredata in swift

To remove an existing record from CoreData in Swift, you can follow these steps:

  1. Fetch the record that you want to delete from the managed object context using a fetch request.
  2. Delete the fetched record by calling deleteObject on the managed object context.
  3. Save the changes to the managed object context using save method.

Here is the sample code to remove an existing record from CoreData:

main.swift
// assume that you've setup the CoreData stack and fetched the record successfully
let recordToDelete = fetchedResultsController.object(at: indexPath)

// delete the record
managedObjectContext.delete(recordToDelete)

// save the changes to the managed object context
do {
    try managedObjectContext.save()
} catch let error as NSError {
    print("Could not save changes. \(error), \(error.userInfo)")
}
407 chars
13 lines

In this code, fetchedResultsController is an instance of NSFetchedResultsController that fetches records from CoreData. indexPath parameter is the index path of the record that you want to delete.

Note: Don't forget to handle the errors when saving the changes to the managed object context.

gistlibby LogSnag