-->

How to create SourceList to show Core Data ToMany

2019-08-12 02:12发布

问题:

Coming from iOS, I am stuck at NSOutlineView as Source list, I have read many resources but cannot grasp it clearly.

What I want is, just to show coreData ToMany relationship as sourceList using NSTreeController. I am persisting data from text file to disk. Entities and relations are as follow:

Group >> Item >> Description

SourceList Example:

My app do not allow user to create any new Entity, just to view what saved from TextFile. I can do this by NSArrayController but I need to show data in single table with hierarchy. In NSArrayController, I only needed to bind managed object context to Parameter and and object controller to Entity Name. On TableView I needed to bind content and selection indexes to NSArrayController.

How can I bind NSTreeController to SourceList and when children is selected, show another ToMany relation from Item to Description.

回答1:

I can think of two solutions and maybe there is a better one.

Solution 1: Create a subclass of NSTreeController and override

- (NSString *)childrenKeyPathForNode:(NSTreeNode *)node

the managed object is node.representedObject.

Solution 2: Create NSManagedObject subclasses and implement a children method which returns the child relationship.

- (NSSet *)children {
    return self.itemsInGroup;
}

Set childrenKeyPath of the tree controller to 'children'.

I think solution 2 feels wrong, managed objects shouldn't contain code for views, but it is very easy to implement if you already have NSManagedObject subclasses.