To understand the lexical scope of block, I have write the following code
typedef int (^ MyBlock)(void);
MyBlock b[3];
for (int i=0; i<3; i++) {
b[i]=^{return i;};
}
for (int i=0; i<3; i++) {
NSLog(@"%d",b[i]());
}
NSLog(@"----------------------------");
int j=0;
b[0]=^{return j;};
j++;
b[1]=^{return j;};
j++;
b[2]=^{return j;};
for (int i=0; i<3; i++) {
NSLog(@"%d",b[i]());
}
- first time o/p is 2,2,2
- second time o/p is 0,1,2
I am expecting 2,2,2 for both of block execution.
Can anybody please explain me why is it so?
I assume you’ve been reading bbum’s post on blocks and know that your code isn’t correct since you aren’t copying the blocks from the stack to the heap.
That said:
does the following in each iteration:
b[i];{}) has ended, pops whatever was in the stack and resets the stack pointer.The stack grows at the beginning of each iteration, and shrinks at the end of each iteration. This means that all blocks are being created in the same memory address, namely A. This also means that all elements in the
barray end up pointing to the same block, namely the last block that was created. You can test this by running the following code:which should output something like:
All elements point to the same block, the last one created in the memory address A = 0x7fff5fbff9e8.
On the other hand, when you do the following:
there’s no compound statement that defines the same scope for all blocks. This means that each time you create a block its address is further down the stack, effectively assigning a different address to each block. Since all blocks are different, they correctly capture the current runtime value of
j.If you print the address of those blocks as described earlier, you should get an output similar to:
showing that each block is at a different memory address.