Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a block as TargetAction in Objective-C

In this answer: Can I pass a block as a @selector with Objective-C?

Lemnar says you could do this:

id block = [^{NSLog(@"Hello, world");} copy];// Don't forget to -release.

[button addTarget:block
           action:@selector(invoke)
 forControlEvents:UIControlEventTouchUpInside];

Where exactly should it be released? Where I'd like to use it, is in the viewDidLoad method, so viewDidUnload seems like the place to release it, but is there any way to release it without creating an ivar?

like image 211
Jonathan. Avatar asked Dec 27 '22 12:12

Jonathan.


1 Answers

That isn't supported; the invoke method is not public and Blocks are not intended to be used in such a role directly.

File an enhancement request and, as a workaround, use objc_implementationWithBlock() and (IIRC) class_addMethod() to create a block-as-method that will work in target action.

like image 115
bbum Avatar answered Dec 30 '22 00:12

bbum