我有一个从CoreData删除NSManagedObject
的函数(Test
是NSManagedObject
的子类:
public func delete(_ test: Test, completion: @escaping (Bool) -> Void) {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return completion(false) }
let managedContext = appDelegate.persistentContainer.viewContext
do {
managedContext.delete(test)
completion(true)
} catch let error as NSError {
print("Could not delete. \(error), \(error.userInfo)")
completion(false)
}
}
现在,似乎此刻该对象正在从CoreData中删除,但是如果我重新运行应用程序,则刚刚出现的对象将再次出现。尝试删除该对象时我在做什么错?
您必须保存上下文以使更改保持不变,包括删除。
do {
try managedContext.save()
} catch let error as NSError {
print("Unresolved error \(error), \(error.userInfo)")
}