views:

273

answers:

2

I have an NSTableView which is bound to an NSArrayController. I would like to have one of the table columns showing the index of the table row. This is easy enough to do when you implement NSTableDataSource yourself but I can't figure it out with a bound table view. I guess I'm looking here for something like the @count key path which gives me the count of arrangedObjects (that is @index) but this is obviously missing.

Two clarifications:

  1. The index that is shown in each row is the index of that row and not related at all to the way the data is actually arranged in the model or array controller. For example, if the whole data is 10000 items then the indexes should go from 1 to 10000, if the user enters a search term and the table is showing only 4 of the items then the numbers should go from 1 to 4, even if the items shown are actually from all over the original array.
  2. I need this because I was asked to do this by the client :-). The client needs a way to be able to estimate the number of rows before or after a certain row. Hi might, for example, want to know how many rows were added.
+1  A: 

Assuming that you aim to replicate the behavior of iTunes, your column only needs to display 1 to (number of visible rows). It does not actually need to relate to your model at all.

So, give your controller a dynamically-generated array property, and make it depend on the array of actual model objects.

For this property, implement the array accessor methods, with the indexed getter simply computing idx + 1, boxing it up, and returning that object. You may also need to implement the whole-array getter to satisfy KVC.

Make sure the column is set as non-editable, and the binding set to not conditionally set enabled. Otherwise, you'll get an exception (for not having setters for this property) when the user tries to enter a new index for a row.

One note of caution: This may cause problems, as NSTableView doesn't expect its columns to be bound to discrete arrays; it expects all of its columns to be bound to different properties of the model objects in a single array. You may need to bind the content of the table view itself to your array of model objects, in addition to binding the content bindings of the columns, and I've had trouble with that before.

Peter Hosey
+1  A: 

As I understand it, you could choose not to bind that table column, and use a datasource instead. I recall NSTableView supports this sort of "dual mode" operation, but can't find any docs to confirm it.

Mike Abdullah
Thanks! the solution was simple enough. I've added a column which wasn't bound to anything, then I set the dataSource outlet of the whole table view to the file owner and then implemented NSTableDataSource returning the column index when asked for the column contents.
Eyal Redler