How to properly cascade delete managed objects in Core Data?

一曲冷凌霜 提交于 2019-12-30 03:56:22

问题


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.


回答1:


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?




回答2:


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



来源:https://stackoverflow.com/questions/2124022/how-to-properly-cascade-delete-managed-objects-in-core-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!