Search code examples
cocoacocoa-bindingskey-value-observingnsarraycontrollerkey-value-coding

Cocoa binding to a particular item in an array controller


Is it possible using NSArrayController to bind a NSTextField's value to a particular item in the array? In particular, I want to bind to a property on the first item in the array, and show nothing if the array is empty.

Using arrangedObjects.command shows just "(" -- presumably it's trying to show a multi-line string with comma-separated strings for each item. I just want the first one.


Solution

  • Bind the text field to selection.command, and programmatically set the array controller's selection index to 0. You may need to also re-set the selection index to 0 any time you add or remove items to the content array.

    Obviously, this won't work if you're allowing the user to select items within the array controller (you'd need a second array controller). I'm assuming that's not the case, since if it were, I'd expect you to want to show the user-selected object, instead of always the first object.

    EDIT: Better yet, do nothing like this—if the object that is first in the array has some special status, you should make a separate non-array property (in the same object that holds the original array, from which I assume the array controller is getting it) to hold the object that has that status.