简体   繁体   中英

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#). 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 . 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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