Search code examples
objective-cautomatic-ref-countingobjective-c-blocksreference-counting

Why passing a weak reference to a block prevents an object from being retained?


We all know that blocks retain objects they capture. We also know we can avoid this by passing a weak reference to an object into a block. But why it works this way? To retain an object means to increase its retain count by one. Why it makes difference to pass a weak reference? Being weak or strong it will still point to the same object, and this object's retain count will be increased by block. Am I right? So why object's retain count doesn't get increased if we pass a weak reference to an object inside a block? How does it work inside?


Solution

  • You can sort of think of a block as an object which has an "instance variable" for each captured variable, which is initialized with the value of the corresponding captured variable at the time the block is created.

    In ARC, the block's "instance variables" have the same ownership specifier as the corresponding captured variable. So if a captured variable of object-pointer type is __strong (the default), the block's "instance variable" is also __strong, so it retains the object pointed to for the lifetime of the block. If a captured variable of object-pointer type is __strong, the block's "instance variable" is also __weak, hence it is a zeroing weak reference to the object pointed to.