在Objective-C中使用块而不是函数是否有优势? [英] Is there an advantage to using blocks over functions in Objective-C?

查看:98
本文介绍了在Objective-C中使用块而不是函数是否有优势?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道一个块是Objective-C中可重用的可执行代码块。有没有理由我不应该在函数中放入相同的代码块,只是在需要运行代码时调用函数?

I know that a block is a reusable chunk of executable code in Objective-C. Is there a reason I shouldn't put that same chunk of code in a function and just called the function when I need that code to run?

推荐答案

这取决于你想要完成的任务。关于块的一个很酷的事情是它们捕获局部范围。您可以使用函数获得相同的最终结果,但最终必须执行诸如传递充满相关值的上下文对象之类的操作。使用块,您可以这样做:

It depends on what you're trying to accomplish. One of the cool things about blocks is that they capture local scope. You can achieve the same end result with a function, but you end up having to do something like pass around a context object full of relevant values. With a block, you can do this:

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时的值被捕获。

So simply by using the variable num1, its value at the time myBlock was defined is captured.

来自Apple的文档



是传统回调函数的有用替代品两个主要原因:

Blocks are a useful alternative to traditional callback functions for two main reasons:


  1. 它们允许您在稍后在方法实现的上下文中执行的
    调用点。块是
    ,因此通常是框架方法的参数。

  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.

它们允许访问局部变量。而不是使用需要执行操作所需的所有上下文
信息的数据结构的回调
,而只需直接访问本地
变量。

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.


这篇关于在Objective-C中使用块而不是函数是否有优势?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆