NSTableView (Creation and Loading from Code)

NSTableView (Creation and Loading from Code)

A few keypoints on NSTableView.
1. Displays data for a set of related records with rows representing individual records and columns representing the attributes.
2. Tableviews are displayed in a scroll view
3. Table Views do not store its own data, It retrieves the data from a datasource (the datasource can be the controller object or a completely standalone object)

In this Article we will be creating and loading a NSTableView from code without using Binding, Array Controller or Interface builder.

Step 1. Create a New Cocoa Project using xCode
Step 2. Modify the Window of the MainMenu and add a Custom View. This Custom View will be the placeholder on which the Table will be added from Code.
1_XIB_Image

Step 3. Modify the App Delegate class by adding the below code

//
// DDAppDelegate.h
// TableViewDemo
#import <Cocoa/Cocoa.h>
@interface DDAppDelegate : NSObject <NSTableViewDelegate, NSTableViewDataSource,NSApplicationDelegate>
{
    IBOutlet NSView *tableViewPlaceholderView;
}
@property (assign) IBOutlet NSWindow *window;
@end
//
// DDAppDelegate.m
// TableViewDemo
//
//
#import "DDAppDelegate.h"
@implementation DDAppDelegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
      // Insert code here to initialize your application
      [self createTableView];
}

//Placeholder for creation of Data or loading from a Database table or a flat file, Excel,CSV etc
//The data sample given below is for creation of an Array of Dictionaries.
//Each key of the dictionary represents one column in the table to be created.
-(NSArray *)dataArray
{
      NSArray *array = [NSArray arrayWithObjects:
                                          [NSDictionary dictionaryWithObjectsAndKeys:@"1001",@"key1",@"1002",@"key2",@"1003",@"key3",@"1004",@"key4",@"1005",@"key5",@"1006",@"key6",@"1007",@"key7", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"2001",@"key1",@"2002",@"key2",@"2003",@"key3",@"2004",@"key4",@"2005",@"key5",@"2006",@"key6",@"2007",@"key7", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"3001",@"key1",@"3002",@"key2",@"3003",@"key3",@"3004",@"key4",@"3005",@"key5",@"3006",@"key6",@"3007",@"key7", nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"4001",@"key1",@"4002",@"key2",@"4003",@"key3",@"4004",@"key4",@"4005",@"key5",@"4006",@"key6",@"4007",@"key7", nil],
nil];
      return array;
}

-(void)createTableView
{
      NSScrollView *scrollView = [[NSScrollView alloc] initWithFrame:tableViewPlaceholderView.bounds];
      [scrollView setBorderType:NSBezelBorder];
      NSTableView *myTableView = [[NSTableView alloc] initWithFrame:tableViewPlaceholderView.bounds];
      NSTableColumn *tCol;
      int noOfColumns = 7;
      for (int i=0; i<noOfColumns; i++)
      {
            tCol = [[NSTableColumn alloc] initWithIdentifier:[NSString stringWithFormat:@"key%d",i+1]];
            [tCol setWidth:100.0];
            [[tCol headerCell] setStringValue:[NSString stringWithFormat:@"Column %d",i+1]];
            [myTableView addTableColumn:tCol];
      }

      [myTableView setUsesAlternatingRowBackgroundColors:YES];
      [myTableView setGridStyleMask:NSTableViewSolidVerticalGridLineMask];
      [myTableView setGridColor:[NSColor redColor]];
      [myTableView setRowHeight:23.0];
      [myTableView setDelegate:self];
      [myTableView setDataSource:self];
      [myTableView setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleRegular];
      [myTableView setAutoresizesSubviews:YES];

      [scrollView setHasVerticalScroller:YES];
      [scrollView setHasHorizontalScroller:YES];
      [scrollView setAutoresizesSubviews:YES];
      [scrollView setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
      [scrollView setDocumentView:myTableView];
      [tableViewPlaceholderView addSubview:scrollView];
}

// TableView Datasource method implementation
- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
     // NSString *aString = [NSString stringWithFormat:@"%@, Row %ld",[aTableColumn identifier],(long)rowIndex];
     NSString *aString;
     aString = [[self.dataArray objectAtIndex:rowIndex] objectForKey:[aTableColumn identifier]];
     return aString;
}

// TableView Datasource method implementation
- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView
{
    //we have only one table in the screen and thus we are not checking the row count based on the target table view
    long recordCount = [self.dataArray count];
    return recordCount;
}
@end

Build and Run 

Gives the following Output

TableViewDemo_Output

Posted in Cocoa, Objective C Tagged with: , ,
5 comments on “NSTableView (Creation and Loading from Code)
  1. Andre says:

    Hi
    I really like your NSTableView created in code, but don’t seem to get it to work.
    I followed the instructions carefully but notice that the IBOutlet NSView *tableViewPlaceholderView is not connected to anything.

    Do I need to connect it to the custom view ?

    Thank you in advance
    André

    • Debasis Das says:

      Yes you need to connect tableViewPlaceholderView outlet to the custom view in the XIB.
      This is the placeholder view , on top of this view we will add the NSScrollView instance
      once the scroll view is created and you have added the NSTableView instance to the scroll view.

      The scrollview itself is added to the tableViewPlaceholderView using the following line of code
      [tableViewPlaceholderView addSubview:scrollView];

      This should work the moment you make the outlet connection

  2. Debasis Das says:

    Yes you need to connect tableViewPlaceholderView outlet to the custom view in the XIB.
    This is the placeholder view , on top of this view we will add the NSScrollView instance
    once the scroll view is created and you have added the NSTableView instance to the scroll view.

    The scrollview itself is added to the tableViewPlaceholderView using the following line of code
    [tableViewPlaceholderView addSubview:scrollView];

    This should work the moment you make the outlet connection

  3. Ivan says:

    Hello!
    Thanks for example!
    This is first example, which work )))

    But i have question.
    If i want to refresh data of table in other functions, what i must call??

    • Debasis Das says:

      you can refresh the data in any function (lets assume its an action or some function that is triggered by an user event or system event) and then reloadData on the table instance. Hope this helps

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Recent Posts


Hit Counter provided by technology news