0

我很难拼凑足够多的知识片段来实现一个 NSOutlineView,它具有在 NSArray 中定义的静态、永不改变的结构。这个链接很棒,但它并没有帮助我掌握子菜单。我认为它们只是嵌套的 NSArrays,但我不清楚。

假设我们在 NSArray 中有一个 NSArray,定义为

NSArray *subarray = [[NSArray alloc] initWithObjects:@"2.1", @"2.2", @"2.3", @"2.4", @"2.5", nil];
NSArray *ovStructure = [[NSArray alloc] initWithObjects:@"1", subarray, @"3", nil];

文本在 outlineView:objectValueForTableColumn:byItem: 中定义。

- (id)outlineView:(NSOutlineView *)ov objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)ovItem
{
    if ([[[tableColumn headerCell] stringValue] compare:@"Key"] == NSOrderedSame)
    {
        // Return the key for this item. First, get the parent array or dictionary.
        // If the parent is nil, then that must be root, so we'll get the root
        // dictionary.

        id parentObject = [ov parentForItem:ovItem] ? [ov parentForItem:ovItem] : ovStructure;

    if ([parentObject isKindOfClass:[NSArray class]])
        {
            // Arrays don't have keys (usually), so we have to use a name
            // based on the index of the object.

        NSLog([NSString stringWithFormat:@"%@", ovItem]);
            //return [NSString stringWithFormat:@"Item %d", [parentObject indexOfObject:ovItem]];
        return (NSString *) [ovStructure objectAtIndex:[ovStructure indexOfObject:ovItem]];
        }
    }
    else
    {
        // Return the value for the key. If this is a string, just return that.

        if ([ovItem isKindOfClass:[NSString class]])
        {
            return ovItem;
        }
        else if ([ovItem isKindOfClass:[NSDictionary class]])
        {
            return [NSString stringWithFormat:@"%d items", [ovItem count]];
        }
        else if ([ovItem isKindOfClass:[NSArray class]])
        {
            return [NSString stringWithFormat:@"%d items", [ovItem count]];
        }
    }

    return nil;
}

结果是“1”、“(”(可扩展)和“3”。NSLog 显示以“(”开头的数组,因此是第二项。扩展它会由于“超出界限”而导致崩溃。我尝试使用parentForItem:但无法弄清楚将结果与什么进行比较。

我错过了什么?

4

1 回答 1

0

您包含的链接后面的示例显示了一个 NSDictionary 来处理子数组的内容,如果我没看错的话。所以我认为你的 ovStructure 不应该是一个数组,而是一个字典。但是,更根本的是,我认为你真的应该研究一下 NSTreeController。不幸的是,NSTreeController 是出了名的难以使用,但去年进行了改进,甚至我最终也让它工作了。祝你好运。

于 2010-04-19T13:37:31.847 回答