Can I add an NSManagedObject to the selected paren

2019-07-20 06:21发布

问题:

I'm learning Core Data and at the moment just using Interface Builder and the XCode data model (following the Aaron Hillegass Cocoa book examples).

I have an MVC application and core data set up and working within interface builder (no hand-written code yet). I've set up various arraycontrollers, views and buttons to add and remove objects and edit data and determine relationships between objects.

However my object model is strictly hierarchical parent-child (and grandchildren) and each relationship is one-to-many. So when I add a child (or grandchild) I want to automatically assign the parent object currently selected in the main tableView as the parent of the new child object.

Is this possible in interface builder or is this the point where I have to start coding my own methods?

Any pointers on the next step I should be looking to take or how to figure it out myself much appreciated. I'm just a bit stuck and can't find a relevant tutorial or reference.

Perhaps it will help if I describe my document window. It has two tableViews with add/remove buttons. The tableView on the right displays an NSSet of the child objects of the parent objected selected in the tableView on left. I want the add button on the right to add a new object and automatically make it a child of the selected parent object so it appears in the tableView on the right.

At the moment the only methods I can see on the arrayController for the the child objects are add: and remove: but of course they don't connect the new object to the currently selected parent. Do I need to add my own (IBAction) method to the parent object i.e. addChildObject:? Or is there a built in way to add the child automatically within CoreData based on the parent-child relationship?

回答1:

Problem solved. I found a tutorial (albeit a bit dated) describing exactly what I am trying to do:

https://developer.apple.com/cocoa/coredatatutorial/index.html

And after studiously following every step carefully I realised I had done everything right I had just missed one binding: I had only set the Content Set of the child array controller and not its Managed Object Context (to File's Owner). That is the only reason my add button was not adding a new child object! Trivial mistake, but when you are not confident you question you're whole approach rather than looking for a simple error. Sorry for anyone who had to read this but maybe the link to the tutorial will help someone.