Answer the question
In order to leave comments, you need to log in
Objective-c blocks?
Good day, blocks are not a difficult topic for me, I understood them, but I can’t understand how the following code outputs 10 G_G
int i = 10;
void (^block) (int) = ^(int x){
NSLog(@"%d", i);
};
i++;
block (i);
Answer the question
In order to leave comments, you need to log in
There is actually a lot of magic going on there. Your entire stack at the time the block was created is copied to another block of memory. As a result, the variable i in the block is not the same as i outside the block.
UPD. If you want i to be the same everywhere, use __block
__block int i = 10;
void (^block) (int) = ^(int x){
NSLog(@"%d", i); // 11
};
i++;
block (i);
It doesn't look like you would understand. A block is an object! When a block is created, it captures the primitives it uses via closures by value.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question