Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective C: what is a "(id) sender"?

In some IBAction I saw:

- (IBAction)pushButton:(id)sender;

This (id)sender when do I use it?

like image 500
cyclingIsBetter Avatar asked Apr 07 '11 08:04

cyclingIsBetter


3 Answers

(id)sender is the object which sent the message to that selector.

Code example:

- (IBAction)submitButton:(id)sender {
    UIButton *button = (UIButton *)sender;
    [button setEnabled:NO];
    [button setTitle:@"foo" forState:UIControlStateDisabled];
}
like image 26
fulvio Avatar answered Nov 15 '22 04:11

fulvio


Matt Galloway described the meaning of (id) sender in actions on the iPhone Dev SDK forums thusly:

(id)sender is the object which sent the message to that selector. It's like in the delegate functions where you have the control passed in to the function, etc.

You'd use this if you had 2 objects which were calling that selector and you wanted to distinguish between them. Of course, you could just use two different functions, but it's often cleaner and less duplication of code to use one function.

See the UIControl Class Reference for more details.


An example for that, UITextField has a delegate which triggers when the UITextField editing ends:

-(IBAction) editingEnded:(id) sender {
   // the cast goes here, lets assume there's more than one UITextfield 
   // in this Owner and you want to know which one of them has triggered
   // the "editingEnded" delegate
   UITextField *textField= (UITextField*)sender;
   if(textField == iAmTheLastTextField)
   {
     // for example login now.
     [self login];
   }
}
like image 58
22 revs, 4 users 84% Avatar answered Nov 15 '22 05:11

22 revs, 4 users 84%


"sender" is the name of the variable.

"(id)" means that the type of the variable is "id", that stands of "any object" (You can see it as the top of the object hierarchy if you want

The name of the method is pushButton: and require 1 parameter of any kind.

This method will be linked to a button on the UI. The delegate of this UI will receive this call and will have a reference to the UIButton that has made the call. Sometimes you don't need it, sometimes you need to have access to that UIButton to change his properties for instance.

like image 5
Pierre Watelet Avatar answered Nov 15 '22 03:11

Pierre Watelet