Reputation: 1255
I've been trying to delete an NSManagedObject. This is my code:
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "MyEnt")
request.predicate = NSPredicate(format: "SELF = %@", EnttoDelete.objectID)
request.returnsObjectsAsFaults = false
do {
let results = try context.fetch(request)
if results.count > 0 {
for result in results as! [NSManagedObject] {
print ("Ent found")
context.delete(result)
do {
try context.save()
} catch {
print("failed to delete")
}
}
}
} catch {
print ("Error in do")
}
}
Has you see I have de Entitie do be deleted (EnttoDelete) and therefor it's ID (EnttoDelete.objectID). Now I've researchedm even in stackoverflow and I think this should work. But it's not. How can I delete desired entitie?
Upvotes: 0
Views: 523
Reputation: 1255
I think I sort this, doing a different thing:
let app = UIApplication.shared.delegate as! AppDelegate
let context = app.persistentContainer.viewContext
var thisID: NSManagedObjectID = (thatLand?.objectID)!
let object = context.object(with: thisID)
context.delete(object)
do {
try context.save()
} catch {
print("failed to delete")
}
I thinks it's the better solution. Not sure though!
Upvotes: 4