views:

101

answers:

4

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?

+2  A: 

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.

Phlibbo
+4  A: 

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.

Jonathan Grynspan
+7  A: 

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.

Barry Wark
+1  A: 

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.

icespace