Search code examples
objective-cibactionsendernspopupbutton

Objective-C does not execute change method for a NSPopUpButton


I have a view with a popup menu. In the view controller I implemented a method for reading which tag/item is selected by the user.

- (IBAction)popUpChanged:(id)sender
{
    self.item = [sender selectedTag];
}

If I choose a menu entry/item the method popUpChanged is executed.

In another class I have a button. By clicking this button the popup menu of the view controller should be set to the item no. 1. Therefore the button-action executes the following line.

[_viewController.popUp selectItemWithTag: 1];

After executing the selectItemWithTag:1 the popup menu is set to the item 1, like expected. The state/item of the popup menu is change, but the button click does not result in the execution of the method popUpChanged?

Can somebody please explain it to me why the method popUpChanged is not executed?


Solution

  • -popUpChanged: is what you set as the action method for the pop-up menu. Programmatically changing the pop-up menu is not an "action" on that pop-up menu. The action is only triggered for user interactions with the pop-up menu.

    It is a fairly general pattern within Cocoa that programmatic operations on controls don't go through the same pathways as user manipulations of those controls. For example, a control can be disabled so the user can't change it, but you can still change it programmatically. Or a window's delegate can prevent closing the window in its -windowShouldClose:, but programmatically closing the window with -close is not subject to that (although -performClose: is).

    In any case, given that you're programmatically changing the selected item in the pop-up menu, you can programmatically invoke the action method or, more usually, do the same operation as the action method would (e.g. [_viewController.popUp selectItemWithTag: 1]; _viewController.item = 1;).

    Or, even better, bind the pop-up button's selectedTag binding to the view controller's item property and a) eliminate the action method, and b) replace your programmatic manipulation of the pop-up with programmatic setting of the view controller's item property.