Skip to content
kevindelord edited this page Jun 28, 2016 · 10 revisions

How to delete one entity

As explained earlier, when you want to create, update or delete entities, you need a saving context.

This function will delete the current entity and log the reason (if enabled).

The first parameter should explain why the entity is getting removed from the local database.

aPlane.deleteEntityWithReason("flight cancelled", inContext: savingContext)

How to delete multiple entities

If you want to be more radical and remove all entities for the current class you use this function.

Plane.deleteAllEntities(savingContext)

You can also use this function to remove all entities for one given class.

DKDBManager.deleteAllEntitiesForClass(Plane, inContext: savingContext)

Attention, this will delete all entities for all classes will be deleted.

DKDBManager.deleteAllEntitiesInContext(savingContext)

Delete child entities or external assets

The CRUD process or a specific user action might needs to delete an entity.

In most cases, if a parent entity is removed, the child entities need to be removed as well.

Following this concept of cascading removal, the developer can easily remove a complete structure of entities.

For example:

To make sure the passengers of one deleted plane are also removed, override the deleteEntityWithReason:inContext: function.

The expected behavior is to remove any data stored on the disk (like image assets) and to forward the destruction process to its child entities.

override func deleteEntityWithReason(reason: String?, inContext savingContext: NSManagedObjectContext) {

    // Remove extra assets
    AssetManager.removeCachedImage(self.anImageStoreOnTheDevice)

    // Forward the destruction process and its reason to every child entities.
    for passenger in self.passengers {
        passenger.deleteEntityWithReason("parent plane cancelled", inContext: savingContext)
    }

    // Call the super function
    super.deleteEntityWithReason(reason, inContext: savingContext)
}

The super function should be called after removing child and local entitities.