3

I have two entities, Document and Attachment. A document can have many attachments. An attachment can belong to a single document.

For some reason, Core Data is not saving the relationship between a document and its attachments when I do the following:

[document addAttachments:attachments];
[context save:&error];
[context reset];

If I fetch the document after executing the above code, its attachments will be empty. Yet, the attachments are saved.

The relationship is saved if I set the inverse relationship manually:

[document addAttachments:attachments];
for (Attachment *attachment in attachment)
{
    attachment.document = document;
}
[context save:&error];
[context reset];

I thought it wasn't necessary to set a relationship both ways with Core Data. What am I doing wrong?

In case it helps, the relationships are defined as follows:

attachments

  • Transient: NO
  • Optional: YES
  • Destination: Attachment
  • Inverse: document
  • Delete Rule: Cascade
  • Type: To Many
  • Ordered: NO

document

  • Transient: NO
  • Optional: YES
  • Destination: Document
  • Inverse: attachments
  • Delete Rule: Nullify
  • Type: To One

Also tried

  • Using mutableSetValueForKey: instead of the generated accessor.
  • Adding the attachments one by one.
  • Retaining the attachments array, just in case.

Same result.

hpique
  • 119,096
  • 131
  • 338
  • 476

1 Answers1

0

This should work. Maybe these two answers might help Core Data Inverse Relationship Not Being Set

How to get at a relationship items properties in Core Data?

Can you post some code?

Community
  • 1
  • 1
aniruddhc
  • 320
  • 1
  • 3
  • 15
  • Thanks @aniruddhc. I'm not overriding `willChangeValueForKey:withSetMutation:inMutationKind:usingObjects:` or `didChangeValueForKey:withSetMutation:inMutationKind:usingObjects:`. What part of the code would be useful? – hpique Feb 03 '14 at 09:40