We have a Listing entity and a ListingAddress entity in a one-to-many relationship. A ListingAddress shouldn't exist without a Listing. I'd like any ListingAddress that is removed from a Listing's addresses relationship to be deleted from the context. Is that possible, or do I have to do it by hand?
3 Answers
You have to do it by hand.
If the listing is deleted, it's straightforward. See the Relationship Delete Rules. You can set it up to "Cascade" whereby the related object will be automatically deleted. You'll still of course need tosave
any changes made to the context:
Cascade
Delete the objects at the destination of the relationship. For example, if you delete a department, fire all the employees in that department at the same time.
But in your case, where the listing isn't deleted, your orphaned ListingAddress objects have to be cleaned up manually. Here's a couple of posts that cover that issue:

- 1
- 1

- 26,115
- 13
- 104
- 132
-
I thought those were invoked when I delete my Listing - I'm interested in the case where e.g. I set its addresses relationship to an empty NSSet. – Simon Oct 19 '11 at 12:27
-
Thanks. I've tweaked it slightly so it's a direct answer to the question - hope that's OK. – Simon Feb 03 '12 at 16:49
There's no automatic way to delete entities when you remove them from a relationship, but you can do the opposite, You can remove entities from a relationship when you delete them. Use the Nullify delete rule on the ListingAddress entity. It still only requires one line of code. You code the delete, not the remove. Unless it's a many-to-many relationship, that should suit your purpose.

- 8,952
- 6
- 31
- 42
-
Agreed, you need to look at this from the point of removing the entity. Let Core Data manage the relationship integrity. – Marcus S. Zarra Oct 19 '11 at 21:53
You could check in the willSave method if there is any orphaned child of ListingAddress and if there is any, you can set it for deletion
override func willSave() {
super.willSave()
if self.deleted {
return
}
if self.listingInverseRelationship == nil {
self.managedObjectContext?.deleteObject(self)
}
}

- 935
- 6
- 23