Apple documentation on this matter states:
When a block is copied, it creates strong references to object variables used within the block. If you use a block within the implementation of a method:
If you access an instance variable by reference, a strong reference is made to self;
If you access an instance variable by value, a strong reference is made to the variable.
and there is code example:
dispatch_async(queue, ^{
// instanceVariable is used by reference, a strong reference is made to self
doSomethingWithObject(instanceVariable);
});
id localVariable = instanceVariable;
dispatch_async(queue, ^{
/*
localVariable is used by value, a strong reference is made to localVariable
(and not to self).
*/
doSomethingWithObject(localVariable);
});
But to me it makes no sense. How can you access instance variable by value? Don't you always access it via reference? Be it self.myVariable
or just id newName = self.myVariable
, it is always by reference.
Then this example is not too clear what they mean. Why is in first case self retaind and in second case not? It's not used anywhere, so why would block capture it?