tags:

views:

347

answers:

3

I want to pass a variable to he buttonEvent method in the selector.

[button addTarget:messageTableViewController action:@selector(buttonEvent) forControlEvents:UIControlEventTouchUpInside];

How does one do this, say if the variable is uid?

the method signature is -(void)buttonEvent:(NString *)uid;

A: 

First, you need to include the colon in the @selector call:

[button addTarget: messageTableViewController action: @selector(buttonEvent:) forControlEvents: UIControlEventTouchUpInside];

Second, you can't do exactly what you want. The argument passed to buttonEvent: will always be the actual control that was touched. You can use that control to figure out what to do next (ie, either use it directly, or set its tag and use that).

Ben Gottlieb
Actually, the colon is only required if you want to pass the sender. The target-action mechanism for controls supports three different action selector forms (no parameters, the sender, or the sender and event). See http://www.devworld.apple.com/iphone/library/documentation/UIKit/Reference/UIControl_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006779-RH2-SW28
gerry3
A: 

The target-action mechanism will send the sender of the action to the argument of the selector, in your case, the button that was pressed. I don't think there's any way around it.

You will probably want to associate your uid with the button (in a NSDictionary, for example), and fetch it in the action method, for example:

- (void)buttonEvent:(id)sender
{
    NSDictionary *dict = self.buttonToUidDict;
    NSString *uid = [dict valueForKey:sender];
}
Martin Cote
My understanding is that an object must implement copyWithZone: (its Class must conform to the NSCopying protocol) to be used as a key in a dictionary (and UIButton does not).
gerry3
+1  A: 
  1. Store all of your buttons in an array.

  2. Store the arguments you want to pass in another array.

  3. Use the -(IBAction) myAction:(id)sender, and look for your button in the button array (indexOfObject)

  4. Use that index to look up the value you want from your array of uid strings and proceed.

An alternative is to set the .tag integer value for each UIButton to be an index, again into that array of uids.

Kendall Helmstetter Gelner
If the cell is custom, the best approach is to set the current row index in a property on the cell: http://stackoverflow.com/questions/1639361/uibutton-inside-uitableviewcontroller/1639641#1639641
gerry3
Who said anything about cells?
Kendall Helmstetter Gelner
The question implies that the button is on a table view cell.
gerry3