Jason
Jason

Reputation: 14605

NSTreeController with two different core data NSManagedObject entities

I am porting my iOS app to the Mac, and want to set up an NSTreeController to manage a hierarchy of entities. There are two distinct NSManagedObject types in this hierarchy, Group and Item, which have a one-to-many relationship (one Group to many Items). However I am having trouble setting up the NSTreeController; I'm getting an error message:

[<NSManagedObject 0x10029c410> valueForUndefinedKey:]: the entity Item is not key value coding-compliant for the key "items".

It seems that NSTreeController is intended to be set up with one type of NSManagedObject, whose children refers to itself, and that having the children be a different kind of object does not work. Is this correct? If so, what do I need to do to rectify this, while keeping the new data model able to migrate properly from the old data model using lightweight migration? If I am indeed able to accomplish the NSTreeObject with two different kinds of NSManagedObjects, how should I set it up?

Upvotes: 2

Views: 821

Answers (1)

TechZen
TechZen

Reputation: 64428

All entities used in a NSTreeController must respond to a designated children message as set by setChildrenKeyPath:. In this case that would be items. In other words, all your objects in the tree structure must respond to the items message even if the object will never have any children

E.g. Suppose you want to model a filesystem and display it with a NSTreeController. You would have to have a data model that looked like this:

FileSystemObject{
  name:
  parent<<-->FileSystemObject.children
  children<-->>FileSystemObject.parent
}

Folder:FileSystemObject{
}

File::FileSystemObject{
}

Then you would override the provide a custom method for FileSystemObject that would return the count of children. You would provide the method name to the NSTreeController with setCountKeyPath:. Override the method in Folder to return a an actual count of children and override in File to return zero.

This is why the NSTreeController is not well thought of. Unlike other controllers, it breaks encapsulation by forcing you to alter the data model to meet the needs of UI which is very poor practice.

Somebody wrote a replacement tree controller that just automatically assumes that any object that doesn't respond to the children keypath is a leaf and provides an automatic children count of zero. Unfortunately, I can't find it now and can't remember what it was called.

Upvotes: 2

Related Questions