给定模型对象,如何在NSTreeController中找到索引路径?

Ton*_*ony 8 cocoa nstreecontroller nsindexpath

给定NSTreeController表示的模型对象,如何在树中找到它们的索引路径并随后选择它们?这似乎是一个非常明显的问题,但我似乎无法找到它的任何参考.有任何想法吗?

Rob*_*ger 18

没有"简单"的方法,您必须遍历树节点并找到匹配的索引路径,例如:

Objective-C的:

类别

@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    
Run Code Online (Sandbox Code Playgroud)

迅速:

延期

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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 哎哟,这真的很低效.我正在考虑编写一个treecontroller的子类,它保持模型和treenodes之间的映射.或者可能是模型上的一个类别,它保留对相关treenode的引用. (2认同)