Using Cocoa Bindings with NSTableView and NSDictionaryController
Cocoa Bindings are a really useful tool to get your user interface running without having to write a whole lot of code. Most recently, the situation arose where an NSTableView needed to be populated with all the keys and values of an NSDictionary. It seems like this would be beyond the scope of Cocoa Bindings and need to be implemented using the old table data source methods, but it turns out Apple already handled this situation by means of the NSDictionaryController.
In Interface Builder, drag in a NSDictionaryController
from the object library. Bind its Content Dictionary
to the dictionary that you want to display. This example uses a shared user defaults controller in which there is a dictionary named filterGenres
. NSDictionaryController exposes both the keys and values of this dictionary through the arrangedObjects
.
In your table you will have a column for the keys and a column for the values. Bind the first column value to the NSDictionaryController arrangedObjects.key
. You probably don't want the keys to be editable, so uncheck Editable
in the Attributes Inspector pane.
Bind the second column to arrangedObjects.value
. If this is going to be editable, make sure to check "Validates Immediately."
You can also bind to NSDictionaryController's arrangedObjects.localizedKeys
. You can set these up as a user friendly description of a setting instead of the actual key you use in your source code.
Never underestimate the power of Cocoa Bindings. They take care of so much hassle so you can focus your code on the real custom behavior of your application.
More information can be found in the class documentation for NSDictionaryController.