简体   繁体   English

在Objective-C中,此块有多大意义?

[英]How much sense does this block make, in Objective-C?

From the docs : 文档

int (^Multiply)(int, int) = ^(int num1, int num2) {
    return num1 * num2;
};
int result = Multiply(7, 4); // result is 28

It only looks complicated - the same thing could be done with an function, or not? 它看起来很复杂-可以用一个函数来完成同一件事吗? What's the real point here in this example? 在此示例中,真正的意义是什么?

Blocks' power is as lexical closures (also known as lambdas in languages such as Python or C#). Blocks的功能就是词汇闭包(在Python或C#等语言中也称为lambda)。 Thus, you can do 因此,您可以

// within other code

int myVar;

int (^multiplyClosure)(int) = ^(int num1) {
    return num1 * myVar;
};

You can then pass this block around and it will keep a (copy) of myVar . 然后,您可以传递块,它将保留myVar的(副本)。 Thus a closure is really code and context and therein lies the power. 因此,闭包实际上是代码上下文,其中蕴含着强大的力量。

In this particular example, even a function would be inappropriate, as it's basic arithmetic. 在此特定示例中,即使是函数也是基本算法也不合适。 However, the example serves to show you the syntax and calling conventions for blocks. 但是,该示例向您展示了块的语法和调用约定。

Blocks themselves are more useful as callbacks or as "drag and drop code." 块本身作为回调或“拖放代码”更有用。 They are a way to do delegation and code extension without having to build stateful functions or delegate classes, and without having to provide the ubiquitous void *contextInfo argument to every callback. 它们是一种进行委派和代码扩展的方法,而不必构建有状态的函数或委托类,也不必为每个回调提供无处不在的void *contextInfo参数。

The point of this example is to show you, how blocks are created and what they can do. 该示例的目的是向您展示如何创建块以及它们可以做什么。 It's like the "hello world" example which you will find in almost every book but not in a real application. 这就像“ hello world”示例,几乎在每本书中都可以找到,但在实际应用中却找不到。 It's just there to illustrate a concept. 它只是用来说明一个概念。

There is no synchronization issue in block. 块中没有同步问题。 Considering you are doing things in multithread, the two parameters of "Multiply" are shared by other threads. 考虑到您在多线程中运行,“ Multiply”的两个参数由其他线程共享。 They will not be modified by other thread since they are in "closure", so you don't need to lock sth and it will keep code simple. 由于它们处于“关闭”状态,因此不会被其他线程修改,因此您无需锁定sth,它将使代码保持简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM