删除所有核心数据记录不设置managedContext中的hasChanges

Delete all core data records does not set hasChanges in managedContext

我是 coreData 的新手,遇到了一个问题:

我的应用程序执行以下 3 个连续的核心数据函数:

    let managedContext = persistentContainer.viewContext
    deleteAllCDRecords(managedContext: managedContext, in: "CDShoppingItem")
    saveManagedContext(managedContext: managedContext)  

它们被定义(简称)为:

private func deleteAllCDRecords(managedContext: NSManagedObjectContext, in entity: String) {
    let deleteFetch = NSFetchRequest<NSFetchRequestResult>(entityName: entity)
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: deleteFetch)
    do {
        try managedContext.execute(deleteRequest)
    } catch let error as NSError {
        // error handling
    }
} // deleteAllCDRecords  

private func saveManagedContext(managedContext: NSManagedObjectContext) {
    if !managedContext.hasChanges { return }
    do {
        try managedContext.save()
    } catch let error as NSError {
        // error handling
    }
} // saveManagedContext  

问题:

deleteAllCDRecords执行后,函数saveManagedContext中的managedContext.hasChanges不成立,因此删除不保存到持久化存储.

我的问题:
我的代码有什么问题?

批量删除在持久存储本身中操作。所以在这种特殊情况下,您从持久存储中删除实体,然后必须删除内存中的对象。

Batch deletes run faster than deleting the Core Data entities yourself in code because they operate in the persistent store itself, at the SQL level. As part of this difference, the changes enacted on the persistent store are not reflected in the objects that are currently in memory.

After a batch delete has been executed, remove any objects in memory that have been deleted from the persistent store.

https://developer.apple.com/library/archive/featuredarticles/CoreData_Batch_Guide/BatchDeletes/BatchDeletes.html