Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly cascade delete managed objects in Core Data?

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:

  1. I delete an instance of A (using deleteObject:)
  2. The delete propagates to any B's associated with A (due to the "Cascade" delete rule)
  3. All B's associated with A are deleted
  4. 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.

like image 228
CJ. Avatar asked Jan 23 '10 17:01

CJ.


2 Answers

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?

like image 67
Sixten Otto Avatar answered Oct 12 '22 02:10

Sixten Otto


Based on the

Any relationships belonging to C's whose associated B's were deleted, are also removed Suggests that the B-C should also have Cascade.

Further, if B is removed, then C's should also be deleted. Again Cascade.

  • Nullify is often used as an inverse deletion rule*

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

like image 29
Gabe Rainbow Avatar answered Oct 12 '22 02:10

Gabe Rainbow