James Pickup
James Pickup

Reputation: 3

How to pass variable to new method I call when using @selector(methodname)

Ok very quick question. I am adding annotations to my iOS using MKMapAnnotation. I create a int and an annotation with a disclosure button Which calls the method loadPano like so:

int integervariable;
[disclosureButton addTarget:self 
                     action:@selector(loadPano) 
           forControlEvents:UIControlEventTouchUpInside];    

Now say I want to access the integer variable in the method load pano how would I do this, I am struggling to understand how I would pass the variable to the new method when it is called like the above.

Upvotes: 0

Views: 233

Answers (4)

newacct
newacct

Reputation: 122519

There are several solutions:

  1. Use the tag. But this can only be an integer.
  2. Add an instance variable (probably accessed using a property) to the class of the button. That means you must make a custom class for the button.
  3. Most general: Use associated objects (a.k.a. associative references), using the runtime functions objc_setAssociatedObject() and objc_getAssociatedObject()

Upvotes: 1

ehope
ehope

Reputation: 516

If you just have to pass an integer associated to each disclosurebutton, you can set disclosurebutton.tag = integer value;.

Sort of hacky to pass data around in tags but in simple cases it works.

Also for this to work, declare loadpano this way:

- (void)loadPano:(UIButton*)sender
{
    NSInteger relevantInteger = sender.tag;
   // More code here
}

And set the target like this:

[disclosureButton addTarget:self 
                     action:@selector(loadPano:) 
           forControlEvents:UIControlEventTouchUpInside];    

Note that the method now takes a parameter so the selector includes a colon.

Upvotes: 1

Caleb
Caleb

Reputation: 125017

In the general case, you can create an instance of NSInvocation with your target, selector, and whatever parameters it needs. Then you call the invocation's -invoke method to send the message to the target.

Upvotes: -1

nkongara
nkongara

Reputation: 1229

You can not pass values other than sender and eventType in target-action methods.

The action message may optionally include the sender and the event as parameters, in that order.

If that integerVariable is a constant, then you can set it as a tag for the control from which you are initiating that action (in your case it is disclosureButton).

or

You can take an instance variable in your class, and access that value in loadPano method.

Upvotes: 0

Related Questions