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

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
    评论
shared_ptr和weak_ptr是C++11中的智能指针,它们都用于管理动态分配的内存资源,但有一些区别。 1. 引用计数:shared_ptr使用引用计数来跟踪有多少个指针共享同一个对象。每当创建一个shared_ptr指向一个对象时,引用计数就会增加。当引用计数为0时,对象会被自动删除。而weak_ptr不会增加引用计数,它只是对shared_ptr的一个观察者,不会影响对象的生命周期。 2. 防止循环引用:shared_ptr可能会导致循环引用,即两个或多个对象相互持有shared_ptr指针,导致它们的引用计数永远不会变为0,从而导致内存泄漏。为了解决这个问题,可以使用weak_ptr。weak_ptr允许你观察shared_ptr指向的对象,但不会增加引用计数,因此可以避免循环引用。 3. 使用场景:shared_ptr适用于多个对象共享同一个资源的情况,例如在多个地方使用同一个动态分配的对象。而weak_ptr适用于需要观察shared_ptr指向的对象,但不需要拥有它的情况,例如在缓存中存储对象的引用。 下面是一个示例代码,演示了shared_ptr和weak_ptr的区别[^1]: ```cpp #include <iostream> #include <memory> class B; class A { public: std::weak_ptr<B> bptr; ~A() { std::cout << "~A()" << std::endl; } }; class B { public: std::weak_ptr<A> aptr; ~B() { std::cout << "~B()" << std::endl; } }; int main() { std::shared_ptr<A> pa(new A()); std::shared_ptr<B> pb(new B()); pa->bptr = pb; pb->aptr = pa; return 0; } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值