Delete Data from Coredata Swift
Swift 3.0
Below is the code to delete item and to reload the data.
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
let noteEntity = "Note" //Entity Name
let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let note = notes[indexPath.row]
if editingStyle == .delete {
managedContext.delete(note)
do {
try managedContext.save()
} catch let error as NSError {
print("Error While Deleting Note: \(error.userInfo)")
}
}
//Code to Fetch New Data From The DB and Reload Table.
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: noteEntity)
do {
notes = try managedContext.fetch(fetchRequest) as! [Note]
} catch let error as NSError {
print("Error While Fetching Data From DB: \(error.userInfo)")
}
noteTableView.reloadData()
}
Update on my coding issue with executing a delete of data in swift and coredata. This the code I ended up with that worked.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
switch editingStyle {
case .Delete:
// remove the deleted item from the model
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
context.deleteObject(myData[indexPath.row] as NSManagedObject)
myData.removeAtIndex(indexPath.row)
context.save(nil)
//tableView.reloadData()
// remove the deleted item from the `UITableView`
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
default:
return
}
}
EDIT Above for Swift 2.2 and Xcode 7.3.1
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
switch editingStyle {
case .Delete:
// remove the deleted item from the model
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
context.deleteObject(myData[indexPath.row] )
myData.removeAtIndex(indexPath.row)
do {
try context.save()
} catch _ {
}
// remove the deleted item from the `UITableView`
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
default:
return
}
}
Also need was these two lines of code to be corrected.
var myData: Array<AnyObject> = []
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext