开发者

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

开发者 https://www.devze.com 2023-03-15 22:23 出处:网络
When coding with cocoa I\'ve noticed that it\'s not necessary to have sender parameter when defining IBAction, hence following action:

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

精彩评论

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