1

I have an NSComboBox. I've set an action selector. When the box gets hidden the selector fires, even if the user never touched it. Yes, I need to hide it.

IBOutlet NSComboBox *comboBox;

[comboBox setAction:@selector(onComboBoxSelection:)];

- (void)onComboBoxSelection:(id)sender
{
   NSLog(@"Why does this fire twice");
   //My code doesn't actually set hidden here, it's just for proof while debugging the issue.
   [comboBox setHidden:YES];
}

Why would hiding an NSControl fire it's selector? What's the best way to fix it?

Update: I've fixed it by wrapping the method. But I'd still like to understand why, or other ways to fix it.

- (void)onComboBoxSelection:(id)sender
{
   if(![sender isHidden]{
     NSLog(@"Now only fires once");
     //My code doesn't actually set hidden here, it's just for proof while debugging the issue.
     [comboBox setHidden:YES];
   }
}
estobbart
  • 1,137
  • 12
  • 28

2 Answers2

2

Set a breakpoint in onComboBoxSelection: and look at the backtrace when it's called the second time (type bt in the debugger to see the backtrace). That will explain what's going.

A combo box is both a text field and a popup, and it will fire actions for both. The text field action is fired when editing ends, either by hitting the Return key or when it resigns first responder (e.g., tabbing out to another field).

When you hide the combo box, the text field resigns first responder and fires its action.

What you probably want to do is check if combo box value has actually changed, and only then proceed with hiding the combo box, etc.

Another option is to use data bindings to observe changes to the combo box. Bind the combo box value to a property on your controller. Then implement the property setter in your controller.

Darren
  • 25,520
  • 5
  • 61
  • 71
  • Is it strange that the action selector applies to both controls? Is there a way to only apply it to the selection of the box and not the textfield? – estobbart Dec 06 '12 at 04:34
  • If you don't want to allow the user to type anything, use NSPopupButton instead. If you want finer control of when the user types something or selects something from the popup, implement the corresponding NSComboBoxDelegate and NSTextFieldDelegate methods. In particular, implement `comboBoxSelectionDidChange:` to track changes to the popup selection. – Darren Dec 06 '12 at 16:53
  • I was expecting the delegate methods to behave much like setting the action selector. – estobbart Dec 07 '12 at 17:07
-1

try this [comboBox setHidden:1];

Mohammad Rabi
  • 1,412
  • 2
  • 21
  • 41