如何使用循环处理 NSOutlineViewDataSource

问题描述

我有一个NSOutlineView 填充的 NSOutlineViewDataSource,它是提供的对象模型的薄包装,包含数组、字典和原始类型的混合。

然而,对象模型在其层次结构中有循环。我认为这不应该是一个问题,因为用户不会扩展该节点(或一段时间后感到无聊),但是两条不同的路径指向同一个对象实例,如果父项被扩展(就像它本来的样子)然后子项也被扩展,导致无限循环。

我尝试将条件逻辑放入我的数据源中,如果文档字典键为“父”,则不返回对象。但我在 isItemExpandable 中看到的只是对对象的引用,我不知道键是否为“父”。

我尝试将对象缓存在 NSDictionary 中,使用它们的键,看看我以前是否遇到过它们,这使我能够确定键名并为 isItemExpandable 返回 NO 这部分有效,但作为它们是同一个对象,父对象键被“父”覆盖,更改了 NSOutlineView显示名称并防止“父”键被展开或折叠。

数据源是通过回调填充的,我没有太多上下文来确定对象是父节点还是子节点,更不用说它是否被多次引用了。

我见过一个类似的问题涉及 NSPathIndex 但这似乎是针对数组索引而不是字典键,NSTreeNode一个类似的问题并且似乎没有 NSKeyPath 类.

有人知道如何处理这种情况吗?

解决方法

大纲视图中的每个项目都必须是唯一的。将每个节点包装在 NSTreeNode 或类似的自定义类中。重复的节点再次被包装。例如:

MyObject 是具有属性 NSObjectchildren 子类,但 representedObject 可以是任何东西。

@property NSTreeNode *rootNode;

// setup
self.rootNode = [[NSTreeNode alloc] initWithRepresentedObject:rootObject];
[self.outlineView reloadData];

- (NSInteger)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(NSTreeNode *)item {
    if (!item)
        item = self.rootNode;
    MyObject *object = item.representedObject;
    return object.children.count;
}

- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(NSTreeNode *)item {
    if (!item)
        item = self.rootNode;
    MyObject *object = item.representedObject;
    /*
    // show repeated nodes as leaves
    NSTreeNode *parentItem = item.parentNode;
    while (parentItem) {
        if (parentItem.representedObject == object)
            return NO;
        parentItem = parentItem.parentNode;
    }
    */
    return object.children.count > 0;
}

- (id)outlineView:(NSOutlineView *)outlineView child:(NSInteger)index ofItem:(NSTreeNode *)item {
    if (!item)
        item = self.rootNode;
    if (index >= item.childNodes.count) {
        // create child nodes
        NSMutableArray *childrenArray = item.mutableChildNodes;
        [childrenArray removeAllObjects];
        MyObject *object = item.representedObject;
        for (MyObject *childObject in object.children)
            [childrenArray addObject:[[NSTreeNode alloc] initWithRepresentedObject:childObject]];
    }
    return item.childNodes[index];
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...