简体   繁体   English

如何在 Swift 闭包中保留分配的实例?

[英]How box allocated instance is retained in Swift closure?

I'm trying to understand how box allocated instance are retained.我试图了解如何保留盒子分配的实例。 On the screen here, we在这里的屏幕上,我们

class A {
    deinit {
        print("deleted")
    }
}

var closure: (() -> Void)!

if true {
    var aa: A? = A()
    closure = {
        // Box wraps Optional<A> without creating new variable, it destroyed cuz it follows outer changes to variable
        print(aa)
    }

    aa = nil
}

closure() // output: deleted; nil

That's okey, this is what I expect expect, as i mentioned because -> Box wraps Optional<A> without creating new variable, it destroyed cuz it没关系,这是我所期望的,正如我所提到的,因为 -> Box 包装Optional<A>而不创建新变量,它破坏了它

Next example legit too:下一个例子也是合法的:

class A {
    deinit {
        print("deleted")
    }
}

var closure: (() -> Void)!

if true {
    var aa: A? = A()
    closure = { [weak aa] in
        // creating a weak variable, that ends up when scope is over. That's okay
        print(aa)
    }

}

closure() // output: deleted; nil

But this example, get me confused a bit但是这个例子让我有点困惑

class A {
    deinit {
        print("deleted")
    }
}

var closure: (() -> Void)!

if true {
    var aa: A? = A()
    closure = {
        // Box retains Optional<A> without creating new variable after if scope end, it doesn't destroyed? But why?
        print(aa)
    }
}

closure() // output: Optional(__lldb_expr_27.A)

Why in last example when scope is over, box allocated instance still gets retained?为什么在上一个示例中,当 scope 结束时,盒子分配的实例仍然被保留? Is there some implicit copying when scope is over? scope 结束时是否有一些隐式复制?

This is what I understand is happening.这就是我所理解的正在发生的事情。

When you do当你这样做

var aa: A? = A()

Only self has a strong reference to aa so aa reference count is 1.只有selfaa有强引用,因此aa引用计数为 1。

When you do当你这样做

if true {
    var aa: A? = A()

    closure = {
        print(aa)
    }
}

Because closure requires aa , closure also has a strong reference to aa now so aa reference count is 2.因为closure需要aa ,所以closure现在也有对aa的强引用,所以aa引用计数为 2。

When you go out of scope, self no longer points to aa and its reference count decreases by 1 but aa cannot be deinitialized because its reference count is not 0 since closure strongly references it.当您从 scope 中取出 go 时, self不再指向aa ,并且其引用计数减少 1,但无法取消初始化aa ,因为它的引用计数不为 0,因为闭包强烈引用它。

关闭强弱ARC参考保持周期迅速

ARC 保持循环 swift 闭包 强弱引用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM