Replacing @selector with direct code

Possible duplicate:
Can I pass a block as @selector using Objective-C?

I have this code:

[myButton addTarget:self action:@selector(doSomething:) forControlEvents:UIControlEventTouchUpInside]; 

But since doSomething contains such little code, I was wondering if it is possible to directly put the code here, and not make it run doSomething.

I already tried this:

 [myButton addTarget:self action:^ { /* code here */ } forControlEvents:UIControlEventTouchUpInside]; 

But it just gives the error "sending (void) ^ (void) to an incompatible SEL type".

Is there any way to do this? If so, what is the correct syntax?

Thanks!

+4
source share
2 answers

Well, all your answers use a lot of unnecessary code that is terribly outdated and no longer works.

I found one answer myself, although I adapted and got this:

 [myButton addTarget:[^{NSLog(@"Pressed the button");} copy] action:@selector(invoke) forControlEvents:UIControlEventTouchUpInside]; 

Which works great.

+5
source

It seems possible, but it looked like an ugly hack to me. See this blog post for more details on the solution.

0
source

Source: https://habr.com/ru/post/1440363/


All Articles