How to select items in NSOutlineView without NSTreeController?
Here is how I finally ended up. Suggestions and corrections are always welcome.
@implementation NSOutlineView (Additions)
- (void)expandParentsOfItem:(id)item {
while (item != nil) {
id parent = [self parentForItem: item];
if (![self isExpandable: parent])
break;
if (![self isItemExpanded: parent])
[self expandItem: parent];
item = parent;
}
}
- (void)selectItem:(id)item {
NSInteger itemIndex = [self rowForItem:item];
if (itemIndex < 0) {
[self expandParentsOfItem: item];
itemIndex = [self rowForItem:item];
if (itemIndex < 0)
return;
}
[self selectRowIndexes: [NSIndexSet indexSetWithIndex: itemIndex] byExtendingSelection: NO];
}
@end
Remember to look in superclasses when you can't find something. In this case, one of the methods you need comes from NSTableView, which is NSOutlineView's immediate superclass.
The solution is to get the row index for the item using rowForItem:
, and if it isn't -1 (item not visible/not found), create an index set with it with [NSIndexSet indexSetWithIndex:]
and pass that index set to the selectRowIndexes:byExtendingSelection:
method.