如何使用NSArrayController在NSTableView中填充数据

9

我想使用NSArrayController来填充NSTableView,但是我找不到确切的步骤。

1个回答

33

一个实现这个的方法是使用KVC,利用NSArrayController填充NSTableView。

示例代码:

TestAppDelegate.h

#import <Cocoa/Cocoa.h>

@interface TestAppDelegate : NSObject <NSApplicationDelegate>
{
    IBOutlet NSArrayController *arrayController;
    IBOutlet NSTableView *theTable;
}

@property (assign) IBOutlet NSArrayController *arrayController;
@property (assign) IBOutlet NSTableView *theTable;

- (void) populateTable;

@end

测试AppDelegate.m

#import "TestAppDelegate.h"

@implementation TestAppDelegate

@synthesize arrayController;
@synthesize theTable;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Populate the table once with the data below
    [self populateTable];
}

- (void) populateTable
{
    NSMutableDictionary *value = [[NSMutableDictionary alloc] init];
    // Add some values to the dictionary
    // which match up to the NSTableView bindings
    [value setObject:[NSNumber numberWithInt:0] forKey:@"id"];
    [value setObject:[NSString stringWithFormat:@"test"] forKey:@"name"];

    [arrayController addObject:value];

    [value release];

    [theTable reloadData];
}
@end

现在在接口生成器中创建绑定:

  • 创建一个NSArrayController并将其连接到arrayController
  • 将NSTableView连接到theTable;
  • 选择NSTableView并将TestAppDelegate设置为它的数据源和委托
  • 对于表中的每一列
  • 将其值绑定到arrayController
  • Controller Key 设置为 arrangedObjects
  • Model Key Path 设置为上面的每个键(例如idname)

运行后,现在应该有一行单独的数据。(这是未经测试的代码,但应该可以给出一般想法)

要了解更多关于这些绑定的帮助,请查看此示例.

这里还有一个很好的例子,其中包含如何创建填充NSTableView的图片。


16
非常好的回答,但有少许小的技术争议。通过使用控制器来填充表视图的列时,不需要连接表视图的dataSource和delegate属性。此外,在您的示例代码中并没有使用KVC,而是使用了绑定。虽然绑定机制是基于KVC(以及KVO等)构建的,但您实际上没有在示例中使用任何KVC API,因为您不需要这样做。 - Huperniketes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接