As you might know, Cocoa offers several ways for populating NSTableView with data.
The first approach is to use the NSTableViewDataSource protocol, which we are applying widely in our samples.
The second approach I want to cover today, is using Cocoa Bindings.
What is Cocoa Bindings?
Cocoa Bindings is an amazing technology that allows us to establish a full two-way data binding without writing any “glue” code. Cocoa Bindings widely uses the MVC paradigm, where models encapsulate application data, view display and edit data and controllers mediate between model and view.
So firstly, we will need to implement our own DataTableController, which we can reuse for any future projects.
In order to avoid creating a new sample from scratch, I’ve used our DASimpleSample, from which I removed all code for filling NSTableView using the NSTableViewDataSource protocol.
Implementing our DataTableController:
As the base for our controller, we will take the NSArrayController class.
So, let’s create a new class called DataTableController, inherit it from NSArrayController, add the DADataTable instance variable, which represents our data table and expose it as the read/write property like on code-snipped below:
// DataTableController.h #import |
-(void)setTable:(DADataTable *)newTable {[newTable retain]; [table release]; table = newTable; [self setContent:[table rows]]; } |
-(void)add:(id)object {if(!table)return; DADataTableRow *newRow =[table addNewRow]; [self rearrangeObjects]; [self setSelectedObjects:[NSArray arrayWithObject:newRow]]; } -(void)remove:(id)object {if(!table)return; for(DADataTableRow *row in[self selectedObjects])[table removeRow:row]; [self rearrangeObjects]; [self selectNext:self]; } |
Binding DataTable:
Open MainMenu.xib in *Interface Builder *and add NSArrayController.
For that, you will need to select a column and, in the Binding Inspector tab in the Value section, choose Bind To: Data Table Controller, set arrangedObjects as Controller Key and put the appropriate column name in the Model Key Path combo-box. We should get something like this:
To do that, we have to expand the toolbar of our application, then open the HUD window for our controller by performing a right mouse button click on it and connect add: and remove: actions with the appropriate toolbar buttons. You will see something like this:
-(void)asyncRequest:(DAAsyncRequest *)request didReceiveTable:(DADataTable *)table { workersTable =[table retain]; // set our table...[tableController setTable:workersTable]; } |
[tableController setTable:workersTable]; |