Ios – Coredata delete rule confusion, xcode

core-dataiosiphoneobjective-cxcode

I have a Core Data relationship between two entities, which is like this:

Entity A                        Entity B
aRelationship <-------------->> bRelationship

With the delete rule set to cascade.

Maybe I have this wrong, but I thought that if the delete rule for both of these relationships was set to "Cascade", then when did the following…

[context deleteObject:EntityA];

…it would also delete all the of the Entity B's associated with it. However when I log all of my entity B's it would seem that I am mistaken.

Could someone please shed some light on my confusion?

Thank you very much.

Best Solution

While it's not immediately apparent in the graphical data model editor each recipocal relationship i.e. each

<--> 

...is really two separate relationship each with its own delete rule. Delete rules are activate when an object of the entity with the delete rule is deleted.

So, if in the data model editor you have two entities Alpha and Beta with a relationship:

Alpha.betas<-->>Beta.alpha

… then you really have two relationships like so:

Alpha.betas--(delete rule)-->>Beta.alpha
Beta.alpha--(delete rule)-->Alpha.betas

You never want to set up a delete rule like this:

Alpha.betas--(cascade)-->>Beta.alpha
Beta.alpha--(cascade)-->Alpha.betas

… because deleting any one Beta instance will delete the associate Alpha object which will trigger the deletion of all related Beta objects. Depending on the details of your data model, a reciprocal cascade can delete a big chunk of you data by accident.

What you really want is:

Alpha.betas--(cascade)-->>Beta.alpha
Beta.alpha--(nullify)-->Alpha.betas

Now, when you delete the Alpha object, it will delete all associated Beta objects.

When a cascade is blocked, it is usually a problem with a required relationship. Can't tell for certain without details of the data model.