In the example below, I don't understand why localVariable
is being accessed by value in doSomethingWithObject
. What makes that conversion? How do you distinguish between accessing a variable by value and accessing it by reference? I would like to see more related examples if possible.
The following is an excerpt from Apple's Blocks Programming Topics and shows how instance variables are retained in blocks.
If you use a block within the implementation of a method, the rules for memory management of object instance variables are more subtle:
- If you access an instance variable by reference,
self
is retained;- If you access an instance variable by value, the variable is retained.
The following examples illustrate the two different situations:
dispatch_async(queue, ^{ // instanceVariable is used by reference, self is retained doSomethingWithObject(instanceVariable); }); id localVariable = instanceVariable; dispatch_async(queue, ^{ // localVariable is used by value, localVariable is retained (not self) doSomethingWithObject(localVariable); });