我知道 block 是 Objective-C 中可重用的可执行代码块。有没有理由我不应该把同样的代码块放在一个函数中,而只是在我需要运行该代码时调用该函数?
最佳答案
这取决于您要实现的目标。关于 block 的一个很酷的事情是它们捕获本地范围。您可以使用一个函数实现相同的最终结果,但您最终不得不做一些事情,比如传递一个充满相关值的上下文对象。使用 block ,您可以执行以下操作:
int num1 = 42;
void (^myBlock)(void) = ^{
NSLog(@"num1 is %d", num1);
};
num1 = 0; // Changed after block is created
// Sometime later, in a different scope
myBlock(); // num1 is 42
所以简单地通过使用变量 num1,它在定义 myBlock 时的值被捕获。
来自 Apple 的 documentation :
Blocks are a useful alternative to traditional callback functions for two main reasons:
They allow you to write code at the point of invocation that is executed later in the context of the method implementation. Blocks are thus often parameters of framework methods.
They allow access to local variables. Rather than using callbacks requiring a data structure that embodies all the contextual information you need to perform an operation, you simply access local variables directly.
关于iphone - 在 Objective-C 中使用 block 而不是函数有优势吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8647462/