Core Data: How to propagate changes to relationships, using delete rules
The Core Data framework provides generalized and automated solutions to common tasks associated with objects in your SQLite Database.
In Core Data you can set up a delete rule for delete any relationship in the current entity. Many don't know that you can use a delete rule for propagate changes to a relationship.
Now i will explain you how to do it in XCode.
Step one - create and fill the data model:
Add a Data Model to the solution (right click to the ProjectName/New File/Core Data/Data Model);
Create entities and relationships (i will use this entities, A, A1, B, C and D, like in the picture).
Select the relations (you are using them for propagate changes), in the Utility Panel on the right, click on the Show Data Model Inspector button and after change the Delete Rule to Cascade (i will change the delete rule to cascade only in the relationB, relationC and relationD relationships).
Step two - create NSManagedObject subclasses
Select all entities in the Data Model
Add the NSManagedObject subclasses to the project (right click to the ProjectName/New File/Core Data/NSManagedObject subclasses);
Step three - use your Data Model :)
Step four - propagate changes to relationships
Simply use this code with the current entity
-(void)propagateToCascade:(id)entity
{
//set delete property to "true" [entity setValue:[NSNumber numberWithBool:TRUE] forKey:@"delete"]; //NSEntityDescription for entity NSEntityDescription *entityDescription = [entity entity]; //get relationship NSDictionary *relationsDictionary = [entityDescription relationshipsByName]; //for each relation for (NSString *relationKey in [relationsDictionary allKeys]) { //get relation descriptor NSRelationshipDescription *relationDescription = [relationsDictionary objectForKey:relationKey]; //if current relation has not the "cascade" deletion rule... if([relationDescription deleteRule] != NSCascadeDeleteRule) continue; //...else... //if is a multi-entities-relation (is a NSSet) if([relationDescription isToMany]) { NSMutableSet *relationSet = [entity mutableSetValueForKey:relationKey]; for (id destinationEntityInSet in [relationSet allObjects]) { //recursive call [self propagateToCascade:destinationEntityInSet]; } } //if is a single-entity-relation (is a NSManagedObject) else { [self propagateToCascade:[relationDescription destinationEntity]]; } }
}
Good Luck :)














