Why do I get this crash error when I try to insert a child into my NSTreeController
?
NSTreeController *tree = [NSTreeController new];
NSTreeNode *node1 = [NSTreeNode treeNodeWithRepresentedObject:@{ @"type": @"shirt" }];
// The below method causes mysterious crash
[tree insertObject:node1 atArrangedObjectIndexPath:[NSIndexPath indexPathWithIndex:0]];
Xcode says:
* Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '[object class: NSMutableDictionary] Cannot perform operation because childrenKeyPath is nil' *
Why is causing this error? What is childrenKeyPath and why do I need it (I'm not using interface builder)?
I've made several mistakes here. You should not insert instances of type NSTreeNode
into an NSTreeController
with insertObject
. You use insertObject
to insert a model object, at which point an NSTreeNode
will be automatically created for it.
Also, in your model object, you need to have a property or key which is set as an NSMutableArray
. Then, before you insert any model objects, you set the childrenKeyPath
property of NSTreeController
to equal the name of that property or key.
This is because NSTreeController
and NSTreeNode
are not designed to hold data or child objects themselves, but act as a simple but helpful "map" for the models you've created and retained.
I hope this information helps others because the rest of StackOverflow was oddly silent about it...