Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NSArrayController to fill data in NSTableView

Tags:

objective-c

I want to use NSArrayController to fill the NSTableview, but i am unable to find out the exact procedure.

like image 810
Richa Vijayvargiya Avatar asked Sep 01 '10 10:09

Richa Vijayvargiya


1 Answers

One way to do this is via KVC, using an NSArrayController to populate an NSTableView.

Example Code:

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

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

Now make the bindings in interface builder:

  • Create an NSArrayController & connect it to arrayController
  • Connect the NSTableView to theTable;
  • Select the NSTableView and set TestAppDelegate as its dataSource & delegate
  • For each column in the table
  • Bind its Value to arrayController
  • Set the Controller Key to arrangedObjects
  • Set the Model Key Path to each key from above (e.g. id or name)

When run, there should now be a single data row. (This is untested code, but should give the general idea)

For more help with these bindings check out this example.

Here is also a good example with pictures of how to create a populated NSTableView.

like image 129
phaxian Avatar answered Nov 16 '22 00:11

phaxian