I have a Core Data model which has three entities: A, B, and C. A has a one-to-many relationship with B, and B has a many-to-many relationship with C. The delete rule for A -> B is "Cascade", and B -> A is "No Action". The delete rule for B -> C is "No Action", and C -> B is "Deny".
I am having trouble performing a delete on the A entity. What I want to happen is the following:
- I delete an instance of A (using
deleteObject:
) - The delete propagates to any B's associated with A (due to the "Cascade" delete rule)
- All B's associated with A are deleted
- Any relationships belonging to C's whose associated B's were deleted, are also removed
That may be a little confusing, so let me paraphrase: When an A is deleted, delete all associated B's. And any C's which reference those B's must not reference them any more.
In my testing, I am not seeing the "Cascade" delete rule work for me at all. When I delete an A, I invoke processPendingChanges
immediately afterwards (just to make sure the deletion has been done). Then I compare the number of A's and B's that were in the NSManagedObjectContext before the deletion, and after it. The instance of A has been properly deleted, (the number of total A's is now one less than before the deletion). However, the number of B's remains the same. So, it seems that the "Cascade" delete rule is not being honored.
I know I can manually go through the A -> B relationship, and manually delete each B. However, it seems like this is something Core Data provides for free, so I don't want to do that unless Core Data is insufficient. Any information regarding the use of "Cascade" delete rules is welcome.
I'm certainly no Core Data expert, but reading the documentation on the various delete rule options, it seems to me that you want the B -> C relationship to be Nullify, rather than No Action. Perhaps the Bs aren't going away because the Cs are still holding references to them?
Based on the
Further, if B is removed, then C's should also be deleted. Again Cascade.
ie. Bs relationship to A is Nullify. C relationship to B is Nulllify. Such that when C is deleted, B is NOT deleted. And when B is deleted; A is NOT deleted.
As in this winning drawing.
A--->>B Cascade <---- Nullify
B--->>C Cascade <---- Nullify