David DelMonte David DelMonte - 25 days ago 21
Swift Question

How to Delete a managedObject - not a tableView

I am describing some color information in a Core Data diagram. The entity is a color, and the attributes are color components.

I am struggling with two aspects: how to delete an color object from the graph, and secondly, (bonus question?), how could I identify duplicate colors?

In my AppDelegate, I have a core data stack like this:

lazy var persistentContainer: NSPersistentContainer = {

let container = NSPersistentContainer(name: "DD")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replacing this implementation with code to handle the error appropriately.

fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()

// MARK: - Core Data Saving support

func saveContext () {
print(#function)
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.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)")
}
}
}


and where I'm trying to delete the color, I have this:

func deleteColor(_ sender:UIButton) {

let i : Int = (sender.layer.value(forKey: "index")) as! Int
print(#function, "object to delete: ", i)

let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

colors.remove(at: i)

do {
try managedContext.save()
} catch let error as NSError {
print("Error While Saving Data: \(error.userInfo)")
}

recentColorCollection!.reloadData()
}


Variables are:

var colors = [RecentColorEntity]()
var colorEntity = "RecentColorEntity"


I'm not getting any errors, but the objects are not being deleted.. Can someone help me figure out what I'm doing wrong

Answer
colors.remove(at: i)

just removes the color from your colors array in memory. You need to delete the actual object, like this

context.delete(colorObject)

and save.

Comments