Given model object, how to find the index path in NSTreeController?

Presented model objects that NSTreeController represents, how do you find their pointer paths in a tree and then select them? This seems to be a dazzlingly obvious problem, but I cannot find any reference to it. Any ideas?

+8
cocoa nsindexpath nstreecontroller
source share
2 answers

There is no “easy” way, you need to go through the nodes of the tree and find the corresponding pointer path, for example:

Objective-C:

Category

 @implementation NSTreeController (Additions) - (NSIndexPath*)indexPathOfObject:(id)anObject { return [self indexPathOfObject:anObject inNodes:[[self arrangedObjects] childNodes]]; } - (NSIndexPath*)indexPathOfObject:(id)anObject inNodes:(NSArray*)nodes { for(NSTreeNode* node in nodes) { if([[node representedObject] isEqual:anObject]) return [node indexPath]; if([[node childNodes] count]) { NSIndexPath* path = [self indexPathOfObject:anObject inNodes:[node childNodes]]; if(path) return path; } } return nil; } @end 

Swift:

Extension

 extension NSTreeController { func indexPathOfObject(anObject:NSObject) -> NSIndexPath? { return self.indexPathOfObject(anObject, nodes: self.arrangedObjects.childNodes) } func indexPathOfObject(anObject:NSObject, nodes:[NSTreeNode]!) -> NSIndexPath? { for node in nodes { if (anObject == node.representedObject as! NSObject) { return node.indexPath } if (node.childNodes != nil) { if let path:NSIndexPath = self.indexPathOfObject(anObject, nodes: node.childNodes) { return path } } } return nil } } 
+18
source share

Why not use NSOutlineView to get the parent elements like this:

 NSMutableArray *selectedItemArray = [[NSMutableArray alloc] init]; [selectedItemArray addObject:[self.OutlineView itemAtRow:[self.OutlineView selectedRow]]]; while ([self.OutlineView parentForItem:[selectedItemArray lastObject]]) { [selectedItemArray addObject:[self.OutlineView parentForItem:[selectedItemArray lastObject]]]; } NSString *selectedPath = @"."; while ([selectedItemArray count] > 0) { OBJECTtype *singleItem = [selectedItemArray lastObject]; selectedPath = [selectedPath stringByAppendingString:[NSString stringWithFormat:@"/%@", singleItem.name]]; selectedItemArray removeLastObject]; } NSLog(@"Final Path: %@", selectedPath); 

This will lead to the conclusion: ./ item1 / item2 / item3 / ...

I assume that you are looking for the file path here, but you can configure it for any data source.

-one
source share

All Articles