views:

11394

answers:

4

When an IBAction is called:

-(IBAction) onClick1: (id) sender;

What is passed in the sender? Since it's hooked up through the IB, I'm not really sure. My question is how to get the text of the button to be the passed object (NSString most likely) so that I could call it inside the action implementation.

-(IBAction) onClick1: (id) sender {
  NSLog(@"User clicked %@", sender);
  // Do something here with the variable 'sender'
}
+7  A: 

It's actually:

-(IBAction) onClick1: (id) sender {
  NSLog(@"User clicked %@", sender);
  // Do something here with the variable 'sender'
}

sender is not a NSString, it's of type id. It's just the control that sent the event. So if your method is trigged on a button click, the UIButton object that was clicked will be sent. You can access all of the standard UIButton methods and properties programmatically.

Marc W
Ah, fixed.So from there all I have to do is call the getTitle method? After I cast the id as a UIButton of course?
Organiccat
You actually don't even need to cast it. Such is the beauty of message passing as opposed to method calling in a dynamic language. :-)
Marc W
Oh and I don't think getTitle is the message you are looking for. You would do [sender currentTitle], as Matt said in his answer.
Marc W
What else can you get from the id? Can you get the Inteface Builder "Name" of the object? Is there some docs about what an 'id' contains? I can't find any!!
bobobobo
`id` is just the generic "any object" type. It's basically akin to a `void *` in C/C++ except smarter. It's whatever the sender is. For a button, it would be the `NSButton` instance that sent the message, for instance.
Marc W
+1  A: 

Sender should be defined as type id, not int or NSString. The sender is the actual object that's calling the method; if you hooked it up to a button, it will be a UIButton, if it's a text field, a UITextField. You can use this to get information from the control (for example the text field's current string value), or compare it to an IBOutlet instance variable if you have multiple controls hooked up to the same action method.

Marc Charbonneau
+5  A: 

The sender should be the control which initiated the action. However, you should not assume its type and should instead leave it defined as an id. Instead, check for the object's class in the actual method as follows:

- (IBAction)onClick1:(id)sender {
    // Make sure it's a UIButton
    if (![sender isKindOfClass:[UIButton class]])
        return;

    NSString *title = [(UIButton *)sender currentTitle];
}
Matt Ball
You don't need to cast sender to a UIButton.
Georg
True, you don't need to. I prefer to cast my ids so that the compiler can warn me if I try to send a message to the wrong kind of object.
Matt Ball
A: 

How to get object id of UIButton /?

www.ruu.cc
That doesn't answer this question, so you should ask it as a separate question (and be a *lot* more specific than that, please).
Peter Hosey