Nguyen  Minh Binh
Nguyen Minh Binh

Reputation: 24433

Could I copy "event handler" on objective C?

This maybe a stupid question, but I want to know if I can copy the "event handler" of a control on objective C or not. e.g I have a button "FIRST", this button will fire the method "clickEventHandler" whenever user click it. Now I have a button "SECOND", I just need second button does similar what the first button does no matter what first button does.

Please give me a solution for this. Any recommend are welcome also.

Upvotes: 1

Views: 158

Answers (1)

trojanfoe
trojanfoe

Reputation: 122401

Given the target and action for buttons is generally set using Interface Builder, I think the best solution might be to have a common method which "routes" the event. So have both buttons call:

- (IBAction)eventRouter:(id)sender
{
    // Don't forget to set the button's tag in IB!
    NSInteger tag = [sender tag];

    switch (tag)
    {
    case BUTTON1_TAG:
        [self button1Method:sender];
        break;
    case BUTTON2_TAG:
        [self button2Method:sender];
        break;
    default
        break;
    }
}

You can then change the routing at runtime without the need to edit the buttons in IB.

EDIT (after question from OP):

In order to get the action (and target) from the button programmatically, just access the action and target properties of the NSButtonCell.

NSButton *button = (NSButton *)sender;    // Or perhaps from an IBOutlet
id target = button.cell.target;
SEL action = button.cell.action;

// Call the button's action selector
[target performSelector:action withObject:self];   // or withObject:sender

Upvotes: 2

Related Questions