Ryker Bay Ryker Bay - 5 months ago 21
iOS Question

While block is copied to heap, will the __weak variable is copied to heap with _block_copy() function?

While block,which use the __strong variable outside the block syntax, is copied to heap, the variable is copied to heap with _block_copy() function.

But what would happen while using __weak variable?
such as:

id __weak weakObj = someObj;
someBlock = [^() {
//using __weak variable
} copy];

Answer Source

I have tried this:

testNumber = [[NSNumber alloc] initWithInt:5];

NSNumber *__weak weakObj = testNumber;
id someBlock = [^() {
    NSLog(@"value in block:%ld",(long)weakObj.integerValue);
} copy];

testNumber = [[NSNumber alloc] initWithInt:6];
NSLog(@"value outside:%ld",(long)testNumber.integerValue);
[someBlock invoke];

Result is:

value outside:6
value in block:5


  1. Weak object can be accessed in copied block;

  2. Weak object keeps the original value(memory address reference) after copying.