I have looked around a lot and there doesn't seem to be a clear answer to this? I have a table view controller where when I delete the cell and want it to remove the data show in a second table view controller which it is linked to via segue. So when deleted the core data attribute shapes should be cleared. With the code below I can only get it to delete one key pair in the attribute and not all.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
context!.delete(array[indexPath.row])
array.remove(at: indexPath.row)
let fetchRequest = NSFetchRequest<Notes>(entityName: "Notes")
fetchRequest.predicate = NSPredicate(format: "shape = %@")
saveList()
do {
let shapes = try context!.fetch(fetchRequest)
for shape in shapes {
context!.delete(shape)
let managedObjectData:NSManagedObject = shape as NSManagedObject
context!.delete(managedObjectData)
}
try context!.save()
} catch _ {
// error handling
}
tableView.reloadData()
}
}
Is there a simple way to clear an attribute of all its data?
Yes, the fastest and correct way to achieve this is by using Coredata deletion rules. I guess in CoreData model you have a one to many relations - each color is related to some shape.
Therefore, in the Coredata editor go on the Identity Inspector and set the relation's delete rule to cascade
. This means that once you delete a color, all of its corresponding shapes will be automatically deleted from the Perstistence store, no need to manually deleting them by looping over them!