【问题标题】:NSTableView doesn't populate with array objects until a new object is added via the controller在通过控制器添加新对象之前,NSTableView 不会填充数组对象
【发布时间】:2013-11-05 11:52:19
【问题描述】:

我有一个 NSTableView 和一个数组控制器,如下所示,使用可可绑定:https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/TableView/PopulatingViewTablesWithBindings/PopulatingView-TablesWithBindings.html#//apple_ref/doc/uid/10000026i-CH13-SW3

在 applicationDidFinishLaunching 期间我的应用程序委托中,我在这里有以下 sn-p,初始化数组并用对象填充它

array = [[NSMutableArray alloc] init];

SomeObject* foo = [[Object alloc] init];
foo.text = @"sup";
[array addObject:foo]; //Repeat this a few times

但是,当我构建应用程序并运行它时,我最终得到一个空表。但是,如果我将一个按钮绑定到数组控制器的 add: input 并在运行时单击它(这会将一个新对象添加到数组和表中),那么该表将首先显示新对象,然后是在 applicationDidFinishLaunching 期间添加的对象。

为什么会这样?有没有办法让我的表格无需先添加元素就可以填充?

【问题讨论】:

标签: objective-c arrays cocoa nstableview cocoa-bindings


【解决方案1】:

NSArrayController 不跟踪可变数组的更改,只是更改它正在观察的array 属性。所以你想要做的是:

NSMutableArray  *mutableArray = [[NSMutableArray alloc] init];

SomeObject* foo = [[Object alloc] init];
foo.text = @"sup";
[mutableArray addObject:foo]; //Repeat this a few times

array=mutableArray;

数组控制器将看到 array 被更改为填充数组。

【讨论】:

    【解决方案2】:

    事实证明,我应该:

    1. 将数组控制器作为属性链接到我的应用委托
    2. 将对象添加到数组控制器本身

    这是在我的应用程序 delegate.h 中:

    @property (copy) NSMutableArray *pastes;
    @property (assign) IBOutlet NSArrayController *controller;
    

    和我的应用 delegate.m:

    @synthesize pastes, controller;
    
     - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
        pastes = [[NSMutableArray alloc] init];
    
        [controller addText:@"sup"];
        [controller addText:@"hey"];
        [controller addText:@"hi"];
    }
    

    【讨论】:

      【解决方案3】:

      希望您已经将表格列绑定到数组控制器。因此,您只需获取字典,然后将该值设置为表列的键,然后将该字典添加到可变数组,然后设置您的可变数组。并在你的 windowDidLoad 或 awakeFromNib 方法中包含此代码。

      【讨论】:

        猜你喜欢
        • 2020-06-01
        • 1970-01-01
        • 2017-10-12
        • 2018-12-02
        • 2013-03-10
        • 2020-11-23
        • 2020-07-20
        • 2015-04-02
        • 1970-01-01
        相关资源
        最近更新 更多