Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core data Migration Delete data of entity

I want to do Lightweight migration in core-data. I am adding an attribute to an entity which is working well.

But I want after this particular migration that entity's data (all objects contained in that entity's table) to be deleted.

I gone through this question, but this method is not looking good as I wanted to keep separate the logic of each migration which will be required in future.

I gave a thought to one way that directly rename that entity but not specifying the rename Identifier so that Core data will process it as deletion of an entity and addition of a new entity, but this thing will not become permanent solution for every similar case in future migrations.

Is there any way if I can delete data directly by going through UI of xcdatamodeld or is there any other method?

like image 582
SandeepAggarwal Avatar asked Oct 09 '15 03:10

SandeepAggarwal


People also ask

What is Core Data migration?

Core Data can typically perform an automatic data migration, referred to as lightweight migration. Lightweight migration infers the migration from the differences between the source and the destination managed object models.


1 Answers

I was able to do this, after much frustration of finding a way, using a custom EntityMigrationPolicy via a Mapping Model, setting the Custom Policy for the entity mapping, eg. EntityNameToEntityName, to this policy (ProductName.DeleteEntityPolicy):

// Swift 5
class DeleteEntityPolicy: NSEntityMigrationPolicy {
    override func begin(_ mapping: NSEntityMapping, with manager: NSMigrationManager) throws {
        // Get all current entities and delete them before mapping begins
        let entityName = "EntityName"
        let request = NSFetchRequest<NSManagedObject>(entityName: entityName)
        let context = manager.sourceContext
        let results = try context.fetch(request)
        results.forEach(context.delete)
        try super.begin(mapping, with: manager)
    }
}

More info of approach to set up a custom migration with a mapping model: https://stackoverflow.com/a/40662940

Would love to know if there's a better way/built in way to do this.

like image 52
Ohifriend Avatar answered Oct 05 '22 15:10

Ohifriend