在区块中保留自我有什么害处?(Objective-C,GCD) [英] What's the harm of retain self in block?(Objective-C, GCD)

查看:87
本文介绍了在区块中保留自我有什么害处?(Objective-C,GCD)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多有关如何使用积木和GCD的指南中,总是提到一个技巧:不要将自己保留在积木中.

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

详细信息是在定义块时,如果引用self或self的ivar,则self被该块保留.因此,解决方法是使用__block修饰符获取weakSelfweakIvar.

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.

但是不这样做有什么害处?如果该块保留了self,则应在该块完成时释放self(我对吗?).因此,最终自我的参考数量是平衡的.我知道如果self保留了块,而block保留了self,那将是一个保留周期.block和self都不会被释放.但是如果使用GCD,自我不保留自我,为什么不让自我保留自我?

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?

推荐答案

除非障碍物一直存在,否则保留自我不会有任何危害.如果您正在使用GCD执行该块,然后将其删除,那就可以了.如果self引用了它所保留的块(即self.someBlock = ^{self.x = 2;}),这只是一个问题,因为那样您就有一个保留周期.

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.

我个人喜欢在GCD中保留该块的self(如果使用了),因为您无法真正控制块的执行时间,并且无法取消它,因此,如果self不被保留,它可能在释放self之后执行.

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.

这篇关于在区块中保留自我有什么害处?(Objective-C,GCD)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆