NSTreeController
이 나타내는 모델 오브젝트가 주어지면 트리에서 인덱스 경로를 찾은 다음 그 인덱스 경로를 어떻게 선택합니까? 이것은 눈부신 명백한 문제인 것처럼 보이지만 나는 그것에 대한 어떤 언급도 찾을 수없는 것처럼 보입니다. 어떤 아이디어? 더 "쉬운"방법이 없습니다주어진 모델 객체, NSTreeController에서 색인 경로를 찾는 방법은 무엇입니까?
8
A
답변
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
이 같은 부모 항목을 얻을 수있는 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를 프로그래밍 방식으로 변경할 수 있습니다. 개체가 이미 선택되었다고 가정합니다. 그렇다면 트리 컨트롤러에서 selectionIndexPath를 얻습니다. – stevesliva
아쉽습니다. 실제로 비효율적입니다. 모델과 treenode 사이의 매핑을 유지하는 treecontroller의 하위 클래스를 작성하려고합니다. 또는 연관된 treenode에 대한 참조를 유지하는 모델의 카테고리 일 수 있습니다. – Tony
서브 클래스에서해야 할 일은 트리 노드의 편평한'NSMutableArray'를 유지하는 것입니다. 물론 노드의 모든 수정 사항이 배열에 반영되도록주의해야합니다. –
흠, 나는 모델 객체 나 objectID를'NSTreeNode's에 매핑하는 NSMutableDictionary를 생각했다. 'NSmutableArray'가 betteR을 사용할 수있는 이유가 있습니까? – Tony