objective-c - NSStackBlock 的内存的一个疑问
伊谢尔伦
伊谢尔伦 2017-05-02 09:19:15
0
1
541

很常见的这个关于block 的题

void exampleB_addBlockToArray(NSMutableArray *array) {
    char b = 'B';
    [array addObject:^{
        printf("%cn", b);
    }];
}

void exampleB() {
    NSMutableArray *array = [NSMutableArray array];
    exampleB_addBlockToArray(array);
    void (^block)() = [array objectAtIndex:0];
    block();
}

Without ARC, the block is an NSStackBlock allocated on the stack of exampleB_addBlockToArray(...). By the time it executes in exampleB(), the the block is no longer valid, because that stack has been cleared.

解释只说明了原理。我有一个理解不知道对不对?
NSStackBlock 类似于一个栈“对象”,不像堆上的局部对象变量 在return 返回它,后所指的内容依然不会被释放。所以在函数结束后其实array 所存的对象(point)依然存在,只是所指的内存(内容)被释放掉了?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(1)
滿天的星座

Try to answer, because I am not sure about the non-ARC situation, but my understanding is the same as yours~

According to its explanation, non-ARC blocks are placed on the stack instead of the heap, which is the same as the basic type. In exampleB_addBlockToArray里那个 block 的定义就是int b = 1;这样,保存在数组里的是指向 b 的指针,也就是它的地址&b,也就是一个0x1234567…… something like this.

But b is exampleB_addBlockToArraya local variable of this function. So when this function ends, the memory it used is "released". In fact, it is marked as "the data has been discarded and this memory can be used for it".

When executed, the pointer 0x1234567…… stored in the array is still there, but the memory it points to is no longer under the control of this pointer. It may be that other data has already been written, or there may still be data from just now.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template