Why entries are not deleted until app is restarted or I execute my NSBatchDeleteRequest twice?

风流意气都作罢 提交于 2020-01-03 02:19:36

问题


I'm reading Delete/Reset all entries in Core Data?.

If I follow the steps below, I get an unexpected result:

  1. Call the code below
  2. Then query an entity in the simulator, I will get an entity back!!!
  3. If I call clearCoreDataStore again (or do a restart), only then the value won't be retrieved from core-data

What am I missing?

func clearCoreDataStore() {
    let entities = dataManager.persistentContainer.managedObjectModel.entities
    for entity in entities {
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: entity.name!)
        let deleteReqest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
        do {
            try context.execute(deleteReqest)
        } catch {
            print(error)
        }
    }
    dataManager.saveContext()
}

回答1:


The objects being deleted from the persistent store are probably also in an in-memory object context. If so, that memory context must first be updated to reflect the deletions. A thorough discussion can be found here.

In a nutshell...

deleteRequest.resultType = NSBatchDeleteRequestResultType.resultTypeObjectIDs
let result = try context.execute(deleteRequest) as? NSBatchDeleteResult
let objectIDArray = result?.result as? [NSManagedObjectID]
let changes = [NSDeletedObjectsKey : objectIDArray]
NSManagedObjectContext.mergeChanges(fromRemoteContextSave: changes, into: [context])


来源:https://stackoverflow.com/questions/53823083/why-entries-are-not-deleted-until-app-is-restarted-or-i-execute-my-nsbatchdelete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!