bharath gangupalli
bharath gangupalli

Reputation: 550

Clear all entities of core data DB except one entity

I need to clear all the Core data entity data in the CoreData but not one Entity. i.e that one entity should not be deleted. One way is to clear entity by entity and skin the one needed. But Can we backup or keep the entity in RAM, clear all Db and re-save the entity. Is it possible?

Upvotes: 0

Views: 243

Answers (1)

vadian
vadian

Reputation: 285150

You can batch delete entities with a NSBatchDeleteRequest, the code assumes managedObjectContext as the current managed object context:

let entityNamesToDelete = ["Foo", "Bar", "Baz"]
let persistentStoreCoordinator = managedObjectContext.persistentStoreCoordinator!

do {
    for entityName in entityNamesToDelete {
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: entityName)
        let deleteRequest = NSBatchDeleteRequest(fetchRequest: request)

        try persistentStoreCoordinator.execute(deleteRequest, with: managedObjectContext)

    }
    try managedObjectContext.save()

} catch { print(error) }

Upvotes: 1

Related Questions