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

旧巷老猫 提交于 2019-11-29 06:55:35
Rob Keniger

There's no "easy" way, you have to walk the tree nodes and find a matching index path, something like:

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
    }
}

Why not use the NSOutlineView to get the parent items 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 output: ./item1/item2/item3/...

I'm assuming you are looking for a file path here but you can adjust for whatever your data source may represent.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!