Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is block in memory Objective-C?

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?

like image 798
huangxinyu Avatar asked Mar 10 '23 15:03

huangxinyu


2 Answers

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.

like image 56
cbuchart Avatar answered Mar 16 '23 08:03

cbuchart


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.

  1. Block is basically allocated on the stack, under the condition below:

    • Block captures at least one variable.
    • If you don't assign the block to variable.
  2. Block is going to be allocated on the heap when:

    • Block captures at least one variable.
    • If you assign the block to any variables(Member variable or local variable).
  3. Block is going to be allocated on the static area when:

    • Block captures nothing.

Cheers!

like image 34
maybeiamme Avatar answered Mar 16 '23 07:03

maybeiamme