I have an NSOutlineView
for which I have written the datasource
and delegate
. When I add an item to a group and the group item is in the collapsed state, parentForItem
returns nil
.
Here is the code I used to test this.
- (IBAction)addItemToGroup:(id)sender {
TLItem *theNewItem= [[TLItem alloc] initWithTitle:@"My New Item"];
TLItem *theGroupItem = [self.sourceListItems objectAtIndex:0];
NSMutableArray *theItemList = [theGroupItem children];
[theItemList addObject:theNewItem];
[self.sourceListOutlineView reloadData];
TLItem *newItemParent = [self.sourceListOutlineView parentForItem:theNewItem];
NSLog(@"newItemParent = %@", newItemParent);
}
If theGroupItem is expanded, this method logs this:
newItemParent = TLItem: 0x60800004bbb0
If theGroupItem is collapsed, this method logs this:
newItemParent = (null)
How can I get the parent for the newly added item?
NOTE: I realize this is a silly example, but in my actual code, I need to be able to walk up the tree to find all parents in the hierarchy.
Given that you have written the data source, use that, not the outline view, to navigate the hierarchy. The data source is the authority on the model. The outline view is just a means of presenting some portion of that model. The outline view will not have a complete representation of the model in the general case, and would often need to consult the data source to answer such queries, anyway. So, skip the middle man and go straight to the source, as it were.
If necessary, your item class should have a weak reference to its parent. All operations on the hierarchy (adding children, removing children, moving items from one parent to another, etc.) should go through dedicated methods on the data source which keep that parent reference updated. You should not simply obtain and modify a mutable array of an item's children outside of such hierarchy-manipulation-specific methods.