Search code examples
objective-ccocoacore-dataxcode4uibuilder

CoreData create relationship when binding to NSArrayController


The setup:

CoreData Model

  • Product Entity

    • Attribute "name"
    • Relationship "common" <---> CommonData
  • CommonData Entity

    • Attribute "product_id"
    • Relationship "product" <---> Product Entity

View Setup:

  • I have a NSTableView to display the product entities and it is bound to an NSArrayController
  • There are two buttons "+" and "-" bound to add: and remove: to the respective actions of the NSArrayController.
  • There is an NSObject controller bound to the selection.common content object, with a NSTextView bound to the NSObjectController.

In the Cocoa documentation, it states that the Releationship Entity is not automatically create when, in this case, the product entity is allocated. I can see this behavior when I click the "+" button. The product is added to the NSTableView, but the NSTextView displays "No Context". And, if I create the product and common entities in code, I can see NSTextView display the *product_id* correctly.

I would like to be able to keep the buttons bound to the NSArrayController.

The Question:

  • Is there any way to detect that the new product entity has been created?
  • What is the best way to add the relationship entity when the new product entity is created via a button action?

Solution

  • In this case I don't think merely doing add: will suffice. You should link your Add button to a new action method, and in this action method you should create a Product object and a CommonData object, and then set the "common" of the former to be the latter. At least that's what I would have done.

    In any case, I think that doing some "detection" of a new CommonData object would be way of an overkill in this case.