Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to declare Objective-C blocks as variable

I have a question regarding the best practice for declaring a block as a variable.

Initially I wrote my block variable like this:

id actionHandler = ^(UIAlertAction * action) {
    // Handling code
};

To be later used like so:

UIAlertAction *action = [UIAlertAction actionWithTitle:@"Title"
                                                 style:UIAlertActionStyleDefault
                                               handler:actionHandler];

But when I came across Apple's Working With Blocks guide, I saw I could rewrite it like so:

void (^actionHandler)(UIAlertAction * action) = ^(UIAlertAction * action) {
    // Handling code
};

Is this the 'correct' way to declare it? That is in my opinion not as readable, but I don't have a lot of experience with Objective-C. So what is the best practice for declaring a block as a variable?


Edit: Alright, thanks all for the clarification! Defining a typedef as shown by amin-negm-awad and others seems like a good alternative approach as well.

like image 278
Kymer Avatar asked Jan 05 '23 09:01

Kymer


1 Answers

There is no one-fits-all answer here: when you declare your block variable as id you no longer have compile-time information associated with your block, so calling it manually becomes problematic:

id myHandler = ^(NSString *str) {
    NSLog(@"%@", str);
};
// Error: Called object type id is not a function or function pointer
myHandler(@"Hello");

if you want to make a direct call to the block from your code, you need to cast it back to a block.

On the other hand, if you declare a block variable only so that you could pass it to a function that takes a block as a parameter, using id provides a more readable approach.

like image 127
Sergey Kalinichenko Avatar answered Jan 06 '23 23:01

Sergey Kalinichenko