Search code examples
cocoabindingcocoa-bindingsnsarraycontrollernscombobox

Binding Cocoa NSComboBox value to object


Assuming I have an NSObject subclass representing a country, e.g.

@interface CountryInfo : NSObject

@property (nonatomic, retain) NSString *countryName;

My model contains an NSMutableArray of CountryInfos. I want to bind the array to an NSComboBox. The combo box should display the country name, and allow the user to select a country.

So, I set up my .xib like so:

CountryArrayController (NSArrayController)

ContentArray

  • Bind to: File's Owner > Model Key Path: self.model.countries

NSComboBox

Content

  • Bind to: CountryArrayController > Controller Key: arrangedObjects

Content Values

  • Bind to: CountryArrayController > Controller Key: arrangedObjects > Model Key Path: countryName

So far, so good. Now, how to bind the Value of the NSComboBox? The documentation states:

"An NSString or NSNumber that specifies the value of the NSComboBox."

What does this mean? I note that I can bind this to an NSString on my model, and it will reflect the selected countryName. But I want to bind to the CountyInfo object itself! Whether directly, or through binding to the selection on my array controller: how can I set this up?


Solution

  • I was approaching this wrong - the correct control to use was NSPopUpButton rather than NSComboBox.

    NSComboBox has a different behaviour because it needs to support the scenario where the user directly enters text. NSPopUpButton is designed to only work with a predefined set of values and behaves as expected vis-a-vis it's "selection" bindings.