开发者

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开发者_JAVA百科 that sent the action? Only other situation I can think of is having few objects calling same IBAction. Anything else?


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.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜