Wednesday, February 17, 2010

Synchronizing the selection in two NSTableViews

I have been looking at a problem of synchronizing the selection across two NSTableViews. It took a few attempts to come to a solution that worked as I wanted it to. The idea is to have two table views with the same number of elements - as soon as you make a selection in one the other one updates to show the same items selected.

My first port of call was to hook into the tableViewSelectionDidChange notification. Then when one selection changes you just change the other. This works - but there is a lag. Click in one table the selection changes, the window updates and then the second selection changes.

The solution was to override selectRowIndexes and to use that to trigger the selection in the paired table. This works fine and produces the required results. I was able to 'hack' this in as a proof of concept fairly quickley.

Implementing it 'properly' or rather 'as I wanted it' I dod not want my two tables to carry references to each other - insead I wanted to have this in the controller class. I did this my adding a new protocol to my subclass of the table:

- (void)selectedRowIndexes:(NSIndexSet *)indexes forTableView:(NSTableView *)tableView byExtendingSelection:(BOOL)extend;

Then, by implementing this protocol, I can add the synchronization logic to the controller which is where I want it.

No comments: