OGeek|极客世界-中国程序员成长平台

标题: ios - 删除所有核心数据记录在managedContext中没有设置hasChanges [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-12 15:00
标题: ios - 删除所有核心数据记录在managedContext中没有设置hasChanges

我是 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 不成立,因此删除是未保存到持久存储中。

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



Best Answer-推荐答案


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

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 .

关于ios - 删除所有核心数据记录在managedContext中没有设置hasChanges,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54296652/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4