ios weak和unown,为什么要在依赖自我的地方指定[unown self]?

本文讨论了在iOS编程中,为何推荐使用`unowned self`而非`weak self`来防止引用循环,特别是在block中,避免因对象即将释放时的安全性考虑。[unownedself]确保了在同时销毁时的便利性,但也可能带来nil引用的风险。
摘要由CSDN通过智能技术生成

I want self to be non-nil and I'm sure it will be, during the blocks execution. So why explicitly specify [unowned self] ?

object.executeBlock {

date = self.lastModified

}

vs

object.executeBlock { [unowned self] in

date = self.lastModified

}

Edit:

Well i'm getting down votes so let's try again. Q: Let’s say I have a problem. That problem is that I would like to prevent a reference cycle. I have two options. I could use [unowned self] or I could use [weak self]. My question therefore, is this: from these two options, why would I choose [unowned self] ? Why not choose [weak self] everytime ?

解决方案

"The Language Guide claims you should use unowned if the closure and containing object reference each other and will be destroyed at the same time. Presumably that's to avoid the cost of safely nil'ing out a weak reference in an object that's about to dealloc anyway."

So [unowned self] makes self an an implicitly unwrapped optional, for the convenience of not unwrapping it yourself, at the risk of a crash if of course it is actually nil.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值