Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

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

In some IBAction I saw:

- (IBAction)pushButton:(id)sender;

This (id)sender when do I use it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...