【问题标题】:Dynamic population of a NSTableView with NSDictionaries with unknown keys具有未知键的 NSDictionaries 的 NSTableView 的动态填充
【发布时间】:2011-06-18 14:22:21
【问题描述】:

是否没有“简单”的方法可以将包含具有未知键的 NSDictionaries 的 NSArray 绑定到 NSTableView?

解决这个“常见”问题的最佳方法是什么?

来自c#/asp.net 看来是个很痛苦的操作。

编辑:

为了阐明应用程序的用途:它是一个简单的查询编辑器,可在表格视图中显示查询结果。

我尝试过这个例子:http://www.cocoabuilder.com/archive/cocoa/150245-dynamic-columns-in-nstableview.html

我使用了一个实现 NSTableViewDataSource 协议的对象。

当用户发出第一个查询时,结果会正确显示。但是第二个查询显示了一些奇怪的情况:列没有正确删除,而是添加到现有的列中,但不是全部。

在构建表的方法中,我使用如下内容:

    NSArray *columns = [_resultTableView tableColumns];

    if(columns && [columns count] > 0)
    {
        for( int i=0; i < [columns count]; i++)
        {
            NSTableColumn *col = [columns objectAtIndex:i];
            NSLog(@"removing column: %@", [col identifier]);
            [_resultTableView removeTableColumn:col];
        }
    }


    NSDictionary *dict = [_resultTableDataSource.data objectAtIndex:0];

    NSArray *keys = [[dict keyEnumerator] allObjects];

    for( int i=0; i < [keys count]; i++)
    {
        NSTableColumn *column = [[NSTableColumn alloc] initWithIdentifier:[keys objectAtIndex:i]];
        [column setEditable:NO];
        [[column headerCell] setStringValue:[keys objectAtIndex:i]];
        [_resultTableView addTableColumn:column];
    }

    [_resultTableView setDataSource:_resultTableDataSource];

    [_resultTableView reloadData];

_resultTableDataSource.data 是一个以 NSMutableDictionary 为记录的 NSMutableArray。

【问题讨论】:

  • 据我所知,我必须实现一个 NSTableViewDataSource 并自己构建列,对吗?
  • 我敢打赌,这种方法是一个例子,对吧?

标签: objective-c cocoa dynamic nstableview


【解决方案1】:

查看 NSArrayController 并在 Interface Builder 中配置列。然后就像 1-2-3 一样简单;)

从这里开始并继续阅读 NSArrayController 描述: http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CocoaBindings/Concepts/CntrlContent.html

【讨论】:

  • 谢谢。但我现在不提前列。
  • 我在原始问题中添加了一些注释以供澄清
【解决方案2】:

好简单。

由于我通过引用遍历列,我必须使用 0 作为索引,因为在删除第一列之后,列数已经是负 1。

将循环更改为以下即可解决问题:

    for( int i=0; i < [columns count]; i++)
    {
        NSTableColumn *col = [columns objectAtIndex:0];
        NSLog(@"removing column: %@", [col identifier]);
        [_resultTableView removeTableColumn:col];
    }

【讨论】:

    猜你喜欢
    • 2013-01-17
    • 1970-01-01
    • 2012-12-19
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多