问题描述
我有一个关于将块声明为变量的最佳实践的问题.
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
};
以后可以这样使用:
UIAlertAction *action = [UIAlertAction actionWithTitle:@"Title"
style:UIAlertActionStyleDefault
handler:actionHandler];
但是当我遇到 Apple 的工作使用 Blocks 指南,我发现我可以像这样重写它:
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
};
这是声明它的正确"方式吗?在我看来,这不是那么可读,但我对 Objective-C 没有太多经验.那么将块声明为变量的最佳做法是什么?
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?
好的,谢谢大家的澄清!将 typedef
定义为 shown 由 amin-negm-awad 和其他似乎也是一个不错的替代方法.
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.
推荐答案
这里没有万能的答案:当你将块变量声明为 id
时,你不再有编译期与您的区块相关联的信息,因此手动调用它会出现问题:
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.
另一方面,如果您声明一个块变量只是为了将其传递给一个将块作为参数的函数,则使用 id
提供了一种更具可读性的方法.
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.
这篇关于将 Objective-C 块声明为变量的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!