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

Ric*_*iya 9 objective-c

我想使用NSArrayController来填充NSTableview,但我无法找到确切的过程.

pha*_*ian 32

一种方法是通过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
Run Code Online (Sandbox Code Playgroud)

TestAppDelegate.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
Run Code Online (Sandbox Code Playgroud)

现在在界面生成器中进行绑定:

  • 创建一个NSArrayController并将其连接到arrayController
  • 将NSTableView连接到桌面;
  • 选择NSTableView并将TestAppDelegate设置为其dataSource和delegate
  • 对于表中的每一列
  • 将其值绑定到arrayController
  • Controller Key 设置arrangeObjects
  • 从上面设置每个键的模型键路径(例如idname)

运行时,现在应该有一个数据行.(这是未经测试的代码,但应该给出一般的想法)

有关这些绑定的更多帮助,请查看此示例.

这里也是一个很好的例子,展示了如何创建一个填充的NSTableView.

  • 非常好的和实质性的答案.然而,一些小的技术问题.通过使用控制器来填充表视图的列,没有必要*连接*表视图的dataSource和委托属性.此外,您没有在示例代码中使用KVC,而是使用*绑定*.虽然绑定机制是基于KVC(以及KVO等)构建的,但实际上并没有使用样本中的任何KVC API,因为您不需要. (14认同)