0

I want to hard code a value inside the @selector of a UIButton's action.

When adding a value inside the @selector I get an error saying: Error

This is how you normally add a @selector to a UIButton:

[myButton addTarget:self action:@selector(myFunction::) forControlEvents:UIControlEventTouchDown];

This is what I want to do:

[myButton addTarget:self action:@selector(myFunction:1:) forControlEvents:UIControlEventTouchDown];

How can this be done?

EDIT: rmaddy pointed out a nice answer here: perfomSelector on button and sending parameters

Community
  • 1
  • 1
Aleksander Azizi
  • 9,829
  • 9
  • 59
  • 87
  • Why don't you put the 1 inside myFunction's implementation? If you're hard coding it, there's no need to pass it. – rdelmar Jul 31 '13 at 00:16
  • Thanks rmaddy, that might just be what I was looking for. – Aleksander Azizi Jul 31 '13 at 00:32
  • 1
    Not really related to your question, but I would *highly* recommend not having method signatures in the form of `myFunction::`. One of the great things that Objective-C does is allow your method signatures to say what each argument is. Take the UIColor method `+colorWithRed:green:blue:alpha:` as opposed to `color::::` Which one makes more sense when reading the code? – Simon Goldeen Jul 31 '13 at 00:52

2 Answers2

2

You can't do that. In the abstract, a selector is just a string representing the name of the method you want to have called. In this case, the framework decides what to pass to it.

What are you trying to accomplish with this? Depending upon the answer, you might be able to use the object reference (myButton) itself for comparison in your selector method, or you may be able to set a tag value inside the method on your button in place of the hardwired number.

  • 1
    The answer, then, is that you can't do what you're asking the way that you have shown. Your only other option is to refactor your common code so that you can pass a parameter (e.g. a flag) to indicate whether you're calling it as the result of a button press or from the other place in your code. – buzzardsoft Jul 31 '13 at 00:36
0

What i'd do is to add a tag to the button myButton and set it to 1. Then in the function myFunction id do like this:

-(void)myFunction:(UIButton *)button {
    NSLog(@"%i", button.tag);                // will output 1
}

So the selector should look like this: @selector(myFunction:)

Arbitur
  • 38,684
  • 22
  • 91
  • 128
  • My function gets the button's tag, but I am calling the function from different locations in my code, that's why I want to hard code 1, 2, etc. – Aleksander Azizi Jul 31 '13 at 00:38