我一直在尝试删除NSManagedObject。 这是我的代码:
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")
}
}
你看到我有de Entitie被删除(EnttoDelete),因此它的ID(EnttoDelete.objectID)。 现在我甚至在stackoverflow中进行了研究,我认为这应该有效。但事实并非如此。 如何删除所需的权利?
答案 0 :(得分:1)
我想我会这样做,做一件不同的事情:
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")
}
我认为这是更好的解决方案。虽然不确定!