2

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!

ravron
  • 11,014
  • 2
  • 39
  • 66
Niels Mouthaan
  • 1,010
  • 8
  • 19

2 Answers2

2

Found it!

You also need to implement indexOfItemWithStringValue like this:

- (NSUInteger)comboBox:(NSComboBox *)aComboBox indexOfItemWithStringValue:(NSString *)aString
{
    return [self.temp indexOfObject:aString];
}
Niels Mouthaan
  • 1,010
  • 8
  • 19
0

To set the selected combobox to the selected item for a data source you use the following per the documentation:

[self.comboBox selectItemAtIndex:2];
[_comboBox setObjectValue:[self comboBox:_comboBox 
           objectValueForItemAtIndex:[_comboBox indexOfSelectedItem]]];

However, the main problem is that since you made the data source 'self' it needs to implement the NSComboBoxDataSource protocol. Since your data source of 'self' does not implement this protocol it will not work correctly.

Note that in the above selector when I say [self comboBox:_comboBox] that self is the name of your data source object.

This information can be found here.

trueinViso
  • 1,354
  • 3
  • 18
  • 30
  • It does implement the NSComboBoxDataSource protocol but in the header file. Also the following code: [self.combobox selectItemAtIndex:2]; [self.combobox setObjectValue:[self comboBox:self.combobox objectValueForItemAtIndex:[self.combobox indexOfSelectedItem]]]; Does exactly do the same (wrong) thing. Thanks for your comment but it didn't help me. – Niels Mouthaan Jul 25 '13 at 21:18
  • Didn't see in header and assumed you didn't implement. – trueinViso Jul 25 '13 at 22:50