Search code examples
cocoaenumscocoa-bindingsnscombobox

Binding NSComboBox to enum?


I've got a very simple problem, but the solution is proving very elusive.

Here's what I have:

typedef { foo, bar, baz} EnumType;

@interface SomeObject: NSObject
@property EnumType someEnumValue;
@end

...and a view with an object_controller and an NSComboBox that should display the string name of the someEnumValue of the [object_controller selection] instance.

I realize that I can't directly access the names of the enum values as strings. I've tried creating an NSArray holding the names of the enum values, and binding the ContentValues property to it - this loads the combo box with the property strings, but I can't find any way to relate the enum value in the selected instance to the values in the combo box.

I've also tried using an NSValueTransformer to translate enum values to NSStrings and vice versa, but for the life of me, I can't get it working: most of these attempts result in a thrown exception.

This trivial task has sucked about three hours out of my life. HELP! Thank you!


Solution

  • There are two approaches that I can think of to solve your problem.

    1. Load the array with strings in the same order as it is in your enum. Since you've got rest of the things working querying the NSComboBox for "indexOfSelectedItem" will give you the exact value of the enum. (Note: This works only if your enum starts from zero. Which I guess is the case while looking at your example.)

    2. Since you have created a class to hold the enum value. Add one more property to it which will hold the name of the enum.. Again query the NSComboBox for indexOfSelectedItem.You can now easily get the associated value by accessing object at given index from the arrangedObjects of arrayController that you are using to bind to the combo box.