2012-01-29 39 views

回答

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  

Swift:

擴展

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

哎喲,那真是低效。我正在考慮編寫一個樹型控制器的子類,以保持模型和treenodes之間的映射。或者可能是模型中的一個類別,它保留對相關treenode的引用。 – Tony 2012-01-29 04:46:07

+0

所有你需要在你的子類中做的事情是維護一個扁平的'NSMutableArray'樹節點。當然,你需要小心,節點的所有修改都會反映在你的數組中。 – 2012-01-29 06:00:03

+0

嗯,我正在考慮一個'NSMutableDictionary'將模型對象或objectID映射到'NSTreeNode's,因爲它對於查找來說似乎更有效率。有沒有什麼原因'NSmutableArray'可能工作betteR? – Tony 2012-01-29 16:56:22

-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/...

我假設你在這裏尋找一個文件路徑,但你可以調整你的數據源可能代表的任何東西。

+0

問題是尋找樹中的任何給定對象的NSIndexPath,以便您可以通過編程方式將樹控制器的selectedIndexPath(s)更改爲那個。您假定該對象已被選中。如果是這樣,你只需從樹形控制器中獲取selectionIndexPath! – stevesliva 2014-05-20 21:00:44

相關問題