int b = 100;
NSLog(@"b in stack:%p", &b);
NSString *str1 = @"Hello World";
NSLog(@"&str1 in stack:%p", &str1);
NSLog(@"block:%p", ^(){});
id block = ^(){};
NSLog(@"block in heap: %p", block);
then, the log is here:
b in stack:0x7fff5fbff75c
&str1 in stack:0x7fff5fbff750
block:0x100001170
block in heap: 0x1000011b0
I looked up lots of blogs, many say NSLog(@"block:%p", ^(){});
's block in stack, but why it's different from the first two according to the address logs?
In the first two you are printing the address of the local variable, which is in the stack. In the last two the block is allocated in the heap and you are printing its address. Try NSLog(@"block in heap: %p", &block);
and you'll see it prints the address where the block
variable is stored, instead its content. In the third case you can't do it since you are creating a temporal variable directly on the argument.
If you want to see the memory address of the block, use
@"%@"
than @"%p"
I don't know what you doubt exactly, but I think my answer can help you.
Block is basically allocated on the stack, under the condition below:
Block is going to be allocated on the heap when:
Block is going to be allocated on the static area when:
Cheers!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With