If blocks are objects, how do they maintain their internal state, and what are their advantages over ordinary objects?

My impression was that the blocks would have to resemble first-class functions and allow lambda-calc-style constructs. However, from the previous question I was told that they are actually just objects.

Then I have 2 questions:

  • Besides the ability to have access to their defining area, which I suppose, they make them usable in a way similar to C ++ "friendship", why if someone followed the block instead of an object? Are they lighter? Because, if not, I could also continue to pass objects as parameters instead of blocks.

  • Do blocks have a way to keep internal state? for example, some variable declared inside a block that will retain its value through calls.

+3
source share
2 answers

Besides being able to access their defining area, which, I think, makes them usable in a way similar to C ++ “friendship”, why do I have to go after the block instead of the object?

Flexibility. Less to implement. A block can represent more than a list of parameters or a specific type of object.

Are they lighter?

Not necessary. Just look at them another toolbar tool and use them where necessary (or required).

? , , , .

, , . , , .

NSInvocation block?

+3

[...], .

, ObjC . plain-C, , , . , .

?

- , . ; - , .

? , , , .

, static , :

void (^albatross)(void);
albatross = ^{
            static int notoriety;
            NSLog(@"%d", notoriety++);
        };

albatross();
albatross();
albatross();
albatross();
+2

All Articles