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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With