Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I was under the impression that blocks were supposed to resemble first-class functions and allow for lambda calc-style constructs. From a previous question however, I was told they are actually just objects.

Then I have 2 questions really:

  1. Besides the feature of having access to their defining scope, which I guess makes them usable in a way resembling C++ "friendship", why would one go for a block instead of an object then? Are they more lightweight? Because if not I might as well keep passing objects as parameters instead of blocks.

  2. Do blocks have a way of keeping an internal state? for instance, some variable declared inside the block which will retain its value across invocations.

like image 807
SaldaVonSchwartz Avatar asked Nov 29 '25 16:11

SaldaVonSchwartz


1 Answers

Besides the feature of having access to their defining scope, which I guess makes them usable in a way resembling C++ "friendship", why would one go for a block instead of an object then?

Flexibility. Less to implement. A block is able to represent more than a parameter list or specific object type.

Are they more lightweight?

Not necessarily. Just consider them another tool in the toolbox, and use them where appropriate (or required).

Do blocks have a way of keeping an internal state? for instance, some variable declared inside the block which will retain its value across invocations.

Yes, they are able to perform reference counting as well as copy stack objects. That doesn't necessarily make them lighter-weight to use than an object representing the parameters you need.

Related

What's the difference between NSInvocation and block?

like image 183
justin Avatar answered Dec 02 '25 06:12

justin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!