I have a Core Data model with a Container and Item entities. A Container can have have zero or more Items in it. An Item must belong to at least one Container (but it can be in more than one.)
The relationships look like this:
Container:
Relationship: items, Destination: Item, Inverse: itemContainers
Optional, To-Many Relationship
Delete Rule: Nullify
Item:
Relationship: itemContainers, Destination: Container, Inverse: items
Not-Optional, To-Many Relationship
Delete Rule: Cascade
Problems arise when a Container is deleted. The Item objects in that container are updated, but if the item existed in only one container, the itemContainers property is a set with no objects. Saving the object graph fails because that empty set violates the Item’s not-optional setting for itemContainers.
Of course, it’s easy enough find the Item objects with empty itemContainers using an NSPredicate like “itemContainers.@count == 0”, but it seems like there ought to be a way to configure the model to do this automatically.
So is there an easier/better way?
I don’t think you can specify this behavior in your model, butI instead of making that fetch, you could validate the count of
itemContainersin your Container’s