开发者

What's the harm of retain self in block?(Objective-C, GCD)

开发者 https://www.devze.com 2023-04-08 10:56 出处:网络
In many guide about how to use blocks and GCD, one tip is always mentioned : do not retain self in block.

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消