Mr Aleph
Mr Aleph

Reputation: 1895

NSTAbleView is not displaying contents of the NSMutableArray

In Xcode 4 I created a new Cocoa application called Tabletest, on the xib I added a NSTableView and control-dragged it to the app's delegate object (created automatically when you create the new Cocoa app). I set the table's dataSource and delegate to the app's delegate object called Tabletest App Delegate.

On tabletestAppDelegate.h and tabletestAppDelegate.m I added the (apparently) required

- (int)numberOfRowsInTableView:(NSTableView *)tableView;
- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row;

- (int)numberOfRowsInTableView:(NSTableView *)tableView
{
    return (int)[myArray count];
}

- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(int)row
{
    return [myArray objectAtIndex:row];
}

and declared an NSMutableArray like NSMutableArray * myArray;
Then I control-dragged the table to the .h and created a property like:

@property (assign) IBOutlet NSTableView *myTable;

On the .m file I added the implementation of numberOfRowsInTableView and (id)tableView...

and added:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    myArray = [[NSMutableArray alloc] initWithCapacity:10];
    int i = 0;
    for(i=0; i<10;i++) 
    {
        [myArray insertObject: [NSString stringWithFormat:@"This is string %d!",i+1] atIndex:i];
    }

    NSEnumerator * enumerator = [myArray objectEnumerator];
    id element;

    while((element = [enumerator nextObject]))
    {
        // Do your thing with the object.
        NSLog(@"%@", element);
    }

}

The `NSLog show the array gets filled but the info never shows on the table. What am I missing? I am a complete newbie on Cocoa and I have no idea why adding information to a simple table is so complicated.

Thank for the help.

Upvotes: 0

Views: 1140

Answers (3)

Christian Krueger
Christian Krueger

Reputation: 139

There is another aspect for not displaying contens : If you add a new item to your array programmatically, meaning dynamically at any time in your app (not at the "initialization" phase in applicationDidFinishLaunching ).

In this case, create an IBOutlet to your arraycontroller and call rearrangeObjects

 //  ... adding items to myArray
 [myArray insertObject: yadayada ...];

 // then let the controller rearrange the objects
 [arrayCtrl rearrangeObjects];  

This behaves like a "refresh" of the tableview with the new element.

Upvotes: 0

Helge Becker
Helge Becker

Reputation: 3253

applicationDidFinishLaunching fires when the view is already loaded. At this time your array is empty. Call reloadData for the table should fix that problem.

Upvotes: 2

Mr Aleph
Mr Aleph

Reputation: 1895

I'll answer my own question, add

[_myTable reloadData];

Upvotes: 0

Related Questions