views:

1955

answers:

2

Hi all!

I'm making a simple Todo application in Cocoa. I have added a class (and an NSObject to the XIB) MATodoController:

MATodoController.h

#import <Cocoa/Cocoa.h>


@interface MATodoController : NSObject
{
    IBOutlet NSTableView *table;
}

- (IBAction)addItem:(id)sender;
- (IBAction)removeItem:(id)sender;

@end

MATodoController.m

#import "MATodoController.h"


@implementation MATodoController

- (void)addItem:(id)sender
{

}

- (void)removeItem:(id)sender
{

}

@end

I have an outlet 'table' to an NSTableView and two actions 'addItem' and 'removeItem' called by button clicks.

Is there a way (ofcourse there is a way)How can I add new rows / remove selected rows to and from an NSTableView (users can select multiple rows at once)?

Thanks in advance.

Oh, one more thing: The NSTableView has only one column (which consists of checkboxes).

+3  A: 

In Cocoa, you don't really add/remove rows to a NSTableView directly. In your controller, you might want to adopt the NSTableDataSource protocol, which has 2 important methods you need to implement in order to get this working:

- (int) numberOfRowsInTableView:(NSTableView *)aTableView
- (id) tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(int)rowIndex

These methods will respond to messages the table view sends to it's data source (configured in Interface Builder) in order to populate the table with rows of data. In these method implementations, you will have to return the information that the method requires (the number of rows; the value of a cell in a particular row) by querying whatever data store you've worked out.

Your addItem and removeItem methods will also need to store/delete row data (in whatever representation you've concocted). You might create a new class that represents each row and store them in an NSMutableDictionary, for instance.

Besides Apple's docs, here's a good tutorial for this task.

Good luck!

Clint Miller
Thanks! That tutorial rocks!
Time Machine
+1  A: 

With Cocoa, the easiest way to do this is with bindings. Create an NSArrayController, linked to an instance of NSMutableArray, and bind the NSArrayController to the NSTableView.

CocoaDev gives a good overview of the procedure. You can also read Apple's documentation, and CocoaDev's excellent article on bindings.

e.James