P
P
Petrushka2015-03-10 23:30:47
Objective-C
Petrushka, 2015-03-10 23:30:47

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);

according to the idea, we increased i to 11, and then called the block, so why do we have the old
PS value, I see that in the block it displays i, not x, but does it matter here?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
ManWithBear, 2015-03-10
@petruska

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);

O
one pavel, 2015-03-10
@onepavel

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.

I
iQQator, 2015-03-11
@iDevPro

int i = 10;
        
        void (^block) (int) = ^(int x){
            NSLog(@"%d", x); // i = 10, x = 11 :)
        };
        i++;
        block (i);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question