I know high level concepts about block programming in Obj C. But, I have few doubts in block programming in Obj C code. Few concepts from Block programming are mentioned like below, so my questions on each one are also below:
-
It supports asynchronous operation:
Q: May i know, what it means? What kind of asynchronous operation Block code supports? -
Block code works(executes) independently than the other code:
Q: Does it mean it runs in a different thread? Does this code executes irrespective of other code executes simultaneously? -
Q: What it means block enumeration?
Anyone please teach me on this?
Blocks are used for various things. The way you use them can make them very powerful.
For example, blocks are often used as a way to do what delegate methods usually do, that is they are passed as parameters and stored aside, then called later when some operation is finished. In that way, they can be used as “asynchronous operations” in the fact that they can be called at a later time.
Example of a usage where blocks can be seen as asynchronous is when they are called in a delegate method to make it easier to use than the delegate:
Blocks don’t really execute independently to other code strickly speaking. The are basically function pointers with context addded to capture surrounding variables. They can be executed in whatever thread you want. If you execute them directly in the current thread, like in the example below, they are not concurrent with the other code:
But using GCD, you can add a block to a GCD queue on an independent thread and ask that thread to execute that block. In that sense, the code declared in the block is executed independently from the rest of the application
You can also interpret the think that “block executes independently to other code” in the sense that they capture their contexte and the variables they need, and can be executed later with the values of these varariables captures when the block was created… even if the variables have changed and/or are out of scope:
Hope those little examples helps.