tags:

views:

810

answers:

2

What is considered the best way of handling multiple NSTableViews without using Cocoa Bindings?

In my app, I have two NSTableViews that are sufficiently closely related that I'm using the same object as the delegate and dataSource for both. The problem is both tableViews invoke the same methods. I currently discriminate between the two tableViews on the basis of NSControl -tag.

The deeper I get into this code, the uglier the use of -tag looks. I end up creating largely duplicate code to distinguish between the tableViews in each delegate/dataSource method. The code ends up being distinctly non-object oriented.

I could create a separate object to handle one or the other tableView, but the creation of said object would be a largely artificial construct just to provide a distinct delegate/dataSource.

Is everyone just using Cocoa Bindings now? I'm avoiding Bindings as I would like to hone my Cocoa skills on techniques that are transferrable between Mac OS and iPhone.

+2  A: 

It sounds like you should be using a different delegate object for each view, but the same data source. In other words a single model for distinct view and controller objects.

I don't think this is an artificial distinction because the objects have sufficiently different purposes, but you want to use the same data. The bigger rule you are violating now is that each object should have a single purpose. Each objects' purpose could be to retreive and display the data in a specific way.

Good Luck!

Mark Thalman
+2  A: 

Every delegate/dataSource method for NSTableView passes the instance of NSTableView that's calling it as the first parameter (except for the ones that pass NSNotification objects, in which case the NSNotification's object is the table view instance). Some examples include:

- (int)numberOfRowsForTableView:(NSTableView*)aTableView;

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

- (void)tableViewSelectionDidChange:(NSNotification *)aNotification

If you're using one controller object as a delegate/data source for multiple tables, you can just use that parameter to differentiate between them.

Brian Webster
I'm currently using the NSControl -tag method, sent to the tableView argument that you point out, to distinguish between tableViews. Using -tag seems a bit more definitive than using the tableView argument itself, as I would have to compare the argument to something to determine the tableView.
Jay O'Conor
Yeah, typically you'll also have outlets set up in IB from your controller to the table views anyway, so you can just compare the passed in table view to your outlets to determine which is which.
Brian Webster
This is the best way to handle it. Delegate methods in Cocoa always include the sending object for this very same reason. If you're repeating yourself, try to factor that code out into a private method.
Marc Charbonneau