Eimantas
Eimantas

Reputation: 49354

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?

Upvotes: 0

Views: 407

Answers (2)

EmptyStack
EmptyStack

Reputation: 51374

Doc says,

The sender parameter usually identifies the control sending the action message (although it can be another object substituted by the actual sender). The idea behind this is similar to a return address on a postcard. The target can query the sender for more information if it needs to.

The sender parameter helps if you want any data from it. For example, on UISegmentControl value change, as in @Mark Adams answer. So if you don't want any information from the sender, you can just omit it, as in your - (IBAction)showUserInfo; example.

Upvotes: 2

Mark Adams
Mark Adams

Reputation: 30846

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;
}

Upvotes: 1

Related Questions