-->

comboBoxSelectionDidChange gives me previously sel

2019-05-05 18:56发布

问题:

I am using this notification for NSComboBox. Only problem is when I select a different item in the dropdown it always show previously selected value in the combo box. How can I get the currently selected value. I need to make some controls enable/disable based on the value.

- (void)comboBoxSelectionDidChange:(NSNotification *)notification {
        NSComboBox *comboBox = (NSComboBox *)[notification object];

        NSLog(@"[comboBox stringValue] : %@", [salaryBy stringValue] );
}

回答1:

I got the selected value using:

NSString *strValue = [comboBox itemObjectValueAtIndex:[comboBox indexOfSelectedItem]];


回答2:

I have also noticed this bug and fixed it in a different way. The correct value can be fetched when we read the value in the next run of the main run loop after the comboBoxSelectionDidChange method call as shown below

- (void)comboBoxSelectionDidChange:(NSNotification *)notification{ 

    [self performSelector:@selector(readComboValue:) withObject:[notification object] afterDelay:0];
}

- (void)readComboValue:(id)object
{
   NSString *comboValue = [(NSComboBox *)object stringValue];
   NSLog(@"%@", comboValue);
}

produces the desired result



回答3:

I use these code with success!

Setting up:

@interface YourWindowController : NSWindowController<NSComboBoxDelegate,NSComboBoxDataSource>


- (void)windowDidLoad
{

comboBox.usesDataSource = YES;
comboBox.datasource = self;
comboBox.delegate = self;
[comboBox selectItemAtIndex:0];

}


-(void)comboBoxSelectionDidChange:(NSNotification *)notification
{

NSLog(@"Selection = %@ ",[[array objectAtIndex: (long)[comboBox indexOfSelectedItem]] objectForKey:@"yourkey"]);



}

Hope this help.