NSComboBox Delegation

1000 Views Asked by At

I have an NSComboBox with a datasource and it works perfectly when you click on the triangle and select one of the items by clicking on it. However, I also want it to allow the user to type in the box to select the name using the auto complete. Currently, when the user types, the item I wish to select autocompletes, but does not select.

My thought was that I should implement a delegation method so that when the user types in the combo box and the selection item name autocompletes, leaving the combobox will run the method to then select the item of the same name from the pop up list.

I implemented this delegation method:

- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor {

    NSString *tempString = [outletPerformanceVenue stringValue];

    NSLog(@"New Value = %@",tempString);

    [outletPerformanceVenue selectItemWithObjectValue:tempString];

    return TRUE;
}

However, I received the following compiler error:

*** -[NSComboBoxCell selectItemWithObjectValue:] should not be called when usesDataSource is set to YES

Seems pretty straight forward, but leaves me wondering... what would be the best way to select the item? Should I determine the index of the record in the datasource array which contains this name and then select the combo box item using the same index? Or is there a more direct way?

* EDIT *

A simpler more direct question might be:

If a user types in (rather than selects from the pull down list) the name of an item into the combo box. How can I retrieve the index of that item from the combo box when using a datasource?

To add insult to injury, Apple's documentation says that the selectItemWithObjectValue: should work with internal or external datasources... per here:

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ComboBox/Tasks/SettingComboBoxValue.html

1

There are 1 best solutions below

0
On

Short answer: use the selectItemAtIndex method, or call setStringValue: (NSComboBox inherits from NSTextField) if you really want to use a string.

And just for completeness: I came here because of a related but slightly different issue.

I'll just explain how I built my combobox. I'm not sure if this applies to your situation, but I'm hoping it might help someone.

I implemented the DataSource methods to make completion work, but let bindings do the work for actually setting the value. That way pressing return either autocompletes the item to one of the options, or creates a new value if there is no autocompletion available. The bindings just take care of setting and getting the value.