给定NSTreeController
表示的模型对象,如何在树中找到它们的索引路径并随后选择它们?这似乎是一个非常明显的问题,但我似乎无法找到它的任何参考。有什么想法吗?
答案 0 :(得分:18)
没有“简单”的方法,您必须遍历树节点并找到匹配的索引路径,例如:
<强>目标-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
<强>夫特:强>
扩展
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
}
}
答案 1 :(得分:-1)
为什么不使用NSOutlineView来获取这样的父项:
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);
这将输出:./ item1 / item2 / item3 /...
我假设您在这里寻找文件路径,但您可以调整数据源可能代表的任何内容。