iphone - 在 Objective-C 中使用 block 而不是函数有优势吗?

标签 iphone objective-c ios objective-c-blocks

我知道 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:

  1. 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.

  2. 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/

相关文章:

iphone - 如何在使用 GPS 时减少 iPhone 电池消耗

iphone - 找不到尺寸正确的图标 120 x 120 的图像

ios - subscriberCellularProviderDidUpdateNotifier 从未被调用

ios - Web View 在 Swift 2.0 中不显示内容

ios - 导航栏大标题过渡代表

ios - SearchBar 文本仅工作 viewDidLoad

iphone - 我在 app-Info.plist 中更改了应用程序标识符,然后又将其更改回来,但无法在我的设备上运行

objective-c - 使用 Cocotron 生成 EXE

objective-c - 在 super View 上获取鼠标按下事件

ios - 网络运行后获取小区计数