Search code examples
cocoaibactiontarget-action

Is there any benefit of having (id)sender in IBAction


When coding with cocoa I've noticed that it's not necessary to have sender parameter when defining IBAction, hence following action:

- (IBAction)showUserInfo:(id)sender;

can be declared as

- (IBAction)showUserInfo;

So I'm wondering if there is any other benefit besides having the button/menu item that sent the action? Only other situation I can think of is having few objects calling same IBAction. Anything else?


Solution

  • It can be handy to use the sender argument when you're connecting the method to UI objects whose values can change and you may need to work with.

    For instance if I wired up a method to a UISegmentedControl and set it's control event to UIControlEventValueChanged, I can use the object passed as the sender: argument to obtain it's selected segment index and then, based on the value, make a change in the UI.

    -(IBAction)segmentedControlValueChanged:(id)sender
    {
        UISegmentedControl *control = (UISegmentedControl *)sender;
    
        // Show or hide views depending on the selected index of the segmented control.
        if (control.selectedSegmentIndex == 0)
            someView.hidden = YES;
        else 
            someView.hidden = NO;
    }