Skip to content

Locally Deprecated Entities

kevindelord edited this page Mar 4, 2016 · 6 revisions

A locally deprecated entity is a NSManaged object not saved as not deprecated in the DKDBManager.

An object not saved as not deprecated is:

  • An object where the CRUD process didn't go through (isn't sent by the API anymore?).

  • An object marked as invalid (see Invalid model entities section).

  • An object not marked as not deprecated in the DKDBManager.

  • An object where the CRUD process has a state that equals to .Delete

Remove all deprecated entities for every model class within a specific context.

Call this function within a saving context after executing the CRUD process (e.g refreshing the local database from an API).

DKDBManager.saveWithBlock { (savingContext: NSManagedObjectContext) in

	// CRUD process
	Plane.createEntityFromDictionary(data, inContext:savingContext)

	// Remove all deprecated entities (not set as 'not deprecated')
	DKDBManager.removeDeprecatedEntitiesInContext(savingContext)
}

See also:

Depending on the app and its architecture some entities could get invalid when something important has been removed or updated. Moreover, some could also become invalid after removing the deprecated entities.

In such case, you have to check and remove the deprecated entities manually using deleteIfInvalidInContext:.

class func checkAllDeprecatedEntities(inContext savingContext: NSManagedObjectContext) {

    // Check validity of all planes and remove the invalid ones.
    if let planes = self.allInContext(savingContext) as? [Plane] {
        for plane in planes {
            plane.deleteIfInvalidInContext(savingContext)
        }
    }
}

Override this function to store the current object and all its child relations as not deprecated.

If an entity did not change in the backend but is still sent through the API, your local database needs to save it as not deprecated. But, as explained previously, if nothing changed the cascading update process will stop on the first entity and not forward it the process to its children.

By doing so, the CRUD logic will not reach them and they will not get updated nor saved as not deprecated.

Problem: when the removeDeprecatedEntitiesInContext: occurs those unsaved entities will be removed.

To avoid such problems, override this function, call the super function and forward the process to every child entities.

override func saveEntityAsNotDeprecated() {
	// Call the super function to store the current object
	super.saveEntityAsNotDeprecated()

	// Forward the process to the 'child' entities of the current object.
	for passenger in self.allPassengers {
		(passenger as? Passenger)?.saveEntityAsNotDeprecated()
	}
}

Remark: If a model class does not have any child relations it is not required to override this function.