4

In many guide about how to use blocks and GCD, one tip is always mentioned : do not retain self in block.

The detail is when defining a block, if you reference self or a ivar of self, then self is retained by the block. So the work around is to use __block modifier to get a weakSelf or weakIvar.

But what's the harm of not doing that? If the block retains self, it should release self when the block is finished(Am I right about this?). So ultimately the reference count of self is balanced. I know if self retains the block and the block retains self, it would be a retain cycle.Neither the block and self will be deallocated. But if using GCD, self don't retain the block, why not let the block retain self?

1 Answer 1

8

There is no harm in retaining self unless the block stays around. If you are using GCD to execute the block and then it is removed then that is fine. It is only a problem if self has a reference to the block that it keeps around (i.e self.someBlock = ^{self.x = 2;}) because then you have a retain cycle.

Personally I like the block retaining self (if used) in GCD as you have no real control over when the block executes and it cannot be canceled, so it may execute after self is deallocated if it is not retained.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.