Search code examples
objective-cmacoscocoanscombobox

Strange bug in NSComboBox: selectItemAtIndex does not work correctly when using data source


I've run into a strange problem with the NSComboBox component. Its "selectIndexAtPath" behavior changes depending on the data source:

  • A "fixed" list causes the item to be correctly selected and when I open the list by clicking the arrow-button on the right, it keeps being selected, however;
  • Using a data source causes the item to be correctly selected BUT when I open the list by clicking the arrow-button on the right, the item is still selected for 1/10 second but then gets deselected.

Some code to illustrate:

@interface AppDelegate()

@property (weak) IBOutlet NSComboBox *combobox;
@property (strong, nonatomic) NSArray *temp;

@end

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    self.temp = @[@"Item", @"Item2", @"Item3", @"Item4", @"Item5"];

    /* THIS DOES WORK */
    self.combobox.usesDataSource = NO;
    [self.combobox addItemsWithObjectValues:self.temp];

    /* HOWEVER, THIS DOES NOT WORK */
    self.combobox.usesDataSource = YES;
    self.combobox.dataSource = self;

    [self.combobox selectItemAtIndex:2];
}

#pragma mark - NSComboBoxDataSource methods

- (NSInteger)numberOfItemsInComboBox:(NSComboBox *)aComboBox
{
    return self.temp.count;
}

- (id)comboBox:(NSComboBox *)aComboBox objectValueForItemAtIndex:(NSInteger)index
{
    return self.temp[index];
}

Does anyone knows what causes this? Trying for days now... thanks!


Solution

  • Found it!

    You also need to implement indexOfItemWithStringValue like this:

    - (NSUInteger)comboBox:(NSComboBox *)aComboBox indexOfItemWithStringValue:(NSString *)aString
    {
        return [self.temp indexOfObject:aString];
    }