Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
749 views
in Technique[技术] by (71.8m points)

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

Given model objects that NSTreeController represents, how do you find their index paths in the tree and subsequently select them? This seems to be a blindingly obvious problem, but I can't seem to find any reference to it. Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...