Ich weiß, dass eine __block
Variable aus dem Stapel in den Heap verschoben wird, wenn ein Block, der darauf zugreift, kopiert wurde. Aber der folgende Testcode zeigt mir, dass die Variable __block
in den Heap vor dem Kopieren des Blocks verschoben wird.Warum wird eine __block-Variable in den Heap verschoben, BEVOR der Block kopiert wird?
Das heißt, die vier Ausgänge sind: Stapel => Heap => Heap => Heap, was ist nicht mein erwartetes Ergebnis: Stapel => Stapel => Stapel => Heap.
Könnte mich jemand aufrichten?
__block int x = 0;
int *pointerToX = &x;
//1. It's on the stack
NSLog(@"x's location is on the stack: %p", &x);
int (^block)() = ^{
x += 1;
return x;
};
//2. I think its stack, but it's heap
NSLog(@"x's location is on the %@: %p", (&x == pointerToX ? @"stack" : @"heap"), &x); //it's heap not stack
block();
//3. I think its stack, but it's heap
NSLog(@"x's location is on the %@: %p", (&x == pointerToX ? @"stack" : @"heap"), &x); //it's heap not stack
block = [block copy]; // The variable x will be moved to the heap
//4. I think its stack, but it's heap
NSLog(@"x's location is on the %@: %p", (&x == pointerToX ? @"stack" : @"heap"), &x); //heap
warum Sie trotzdem über diese kümmern? und was passiert mit '__block int x; int * ptr = & x; 'wenn die Variable vom Stack zum Heap verschoben wird? –
Es ist ein Implementierungsdetail. Sie sollten versuchen, nicht zu sehr darüber nachzudenken. –
Das Protokollieren der Klasse des Blocks (ja, Blöcke sind Objekte) ist ebenfalls hilfreich, um zu bestimmen, wo es kopiert wurde ("__NSStackBlock__", "__NSMallocBlock__"). – CodaFi