How to properly cascade delete managed objects in Core Data?

CJ. picture CJ. · Jan 23, 2010 · Viewed 14.3k times · Source

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.

Answer

Sixten Otto picture Sixten Otto · Jan 23, 2010

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?