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

StackOverflow https://stackoverflow.com/questions/17867020

Вопрос

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!

Это было полезно?

Решение

Found it!

You also need to implement indexOfItemWithStringValue like this:

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

Другие советы

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top