0
votes

I have a simple data model: a parent entity in an optional one-to-many relationship with a child entity. The inverse relationship (child -> parent) is mandatory (non-optional).

After a child object is deleted, Core Data refuses to save, complaining about a missing required property in the child entity. The error goes away if the inverse relationship is made optional.

Why can I not have a mandatory inverse relationship where it is logical (i.e. a child must have a parent)? Why Core Data complains about a deleted object's inconsistency? Is this expected behaviour?

Thank you for any clarifications.

Edit: As requested, I am including a picture of my test data model:
Test parent-child Core Data model
As for the question about delete code, there is none. It's all done through NSArrayController bindings set up in the application window nib. You can load the test project here: Parent-child test project. It should probably be mentioned that this project is based on NSPersistentDocument architecture.

The behaviour I observe is as follows: if a parent is created without children, the document can be normally saved. If a child is created and then deleted, there is an error message on trying to save the document:
Parent-child error message

3
Please show us the model, the delete code and the error message.Mundi

3 Answers

3
votes

I've just discovered the answer to my own question.

The problem I was observing with objects lingering after deletion from the associated NSArrayController is related to the default operation of the controller's -remove: and -removeObject:methods. As per Apple docs (NSArrayController -removeObject: method):

If, however, the receiver’s contentSet is bound to a relationship, removeObject: by default only removes the object from the relationship (not from the object graph). You can, though, set the “Deletes Object on Remove” option for the contentSet binding, in which case objects are marked for deletion as well as being removed from the relationship.

This applies equally to the -remove: method. Setting 'Deletes Object on Remove' in the child array controller contentSet binding solves the problem.

0
votes

Maybe you got it the other way round?

The child's to-one relationship to the parent should not be optional.
The parents's to-many relationship to the children should be optional.

I just tested this setup, and it works.

0
votes

Looking at your additional information, one thing pops out: the delete rule.

Let's think for a moment what might happen with the Cascade setting of your children relationship.

Child deleted --> cascade = parent deleted --> possible other orphaned children

Maybe that is what is happening? Try setting the delete rule to Nullify.