user19003768
user19003768

Reputation:

What's the difference with :(id)sender?

What's the difference between declaring a UIButton in Xcode like this:

- (IBAction)testButton;

and declaring a button like this:

- (IBAction)testButton:(id)sender;

I understand that in the .m file you would then implement the buttons accordingly, as shown below:

- (IBAction)testButton
{
// insert code here..
}

and setting it up like this:

- (IBAction)testButton:(id)sender
{
// insert code here..
}

Is there any additional things you can do by declaring the button with :(id)sender, is there some additional stability, or is there no difference?

Upvotes: 1

Views: 1056

Answers (3)

Josh Engelsma
Josh Engelsma

Reputation: 2646

It allows you to know which button you are working with. I have posted a simple example for a card game below

- (IBAction)flipCard:(id)sender {
    [self.game flipCardAtIndex:[self.cardButtons indexOfObject:sender]];
    self.flipCount++;
    [self updateUI];
}

This method is used for a card flipping game. There are multiple buttons on the screen representing different cards. When you hit the button, a card in the model must be flipped. We know which one by finding the index of the variable sender

Upvotes: 0

nhgrif
nhgrif

Reputation: 62062

- (IBAction)someMethod:(id)sender {
    // do stuff
}

Using (id)sender, you have a reference to who sent the method call. Please note, this doesn't have to be limited to a UIButton.

If you're created this method via control-dragging from the storyboard an only hooking up a single button, then sender is basically useless (it will always be the same), and should probably be marked as unused:

#pragma unused (sender)

(The compiler can better optimize your code if you do this.)

However, there's nothing wrong with hooking up several UI elements to the same IBAction method. You can then distinguish the sender via:

[sender tag]

...which returns an int that was either set via the storyboard or programmatically.

Moreover, you can call this method elsewhere in your class. You can either pass nil as the sender, or you can pass it a particular UI element in order to force it into the results you've coded for objects of that tag.

Nonetheless, if you plan to call the method with a nil argument, you can always throw:

if(!sender)

... into the method in order to handle special logic for when the method has been invoked programmatically as opposed to via user interaction.

Upvotes: 2

Choppin Broccoli
Choppin Broccoli

Reputation: 3076

With :(id)sender you are able to access the button itself through the sender variable. This is handy in many situations. For example, you can have many buttons and give each a tag. Then use the [sender tag] method to find which button was tapped if many buttons are using this IBAction.

Upvotes: 5

Related Questions