简体   繁体   English

Swift函数变量需要弱引用吗?

[英]Do Swift functions variables require weak references?

I have an extension method to add an animated border to image views, which I achieve by using CAShapeLayer: 我有一个扩展方法可以向图像视图添加动画边框,这是通过使用CAShapeLayer实现的:

extension UIImageView {

    func addAnimatedBorder () {
        let border = CAShapeLayer()
        //...setup animation
        border.position = self.center
        self.layer.addSublayer(border)
    }
}

Since the CAShapeLayer is referencing the UIImageView (through its position), and the UIImageView has the CAShapeLayer as a layer, I'm worried there will be a retain cycle. 由于CAShapeLayer(通过其位置)引用UIImageView,并且UIImageView将CAShapeLayer作为图层,因此我担心会存在保留周期。

Do I need to declare the "border" -- the CAShapeLayer -- as weak? 我是否需要宣布“边界”(CAShapeLayer)为弱? Or will that go out of scope once the function executes, leaving the only reference to the object being the one from the UIImageView? 还是在函数执行后就超出范围,而对对象的唯一引用就是UIImageView中的引用?

Or will that go out of scope once the function executes 否则函数执行后会超出范围

Exactly so. 正是如此。 This is a local variable , meaning that it has automatic memory management — a fancy term that simply means it will go out of existence when we exit the scope. 这是一个局部变量 ,意味着它具有自动内存管理功能–一个花哨的术语,仅仅意味着它在我们退出范围时将不复存在。 In this case, exiting the scope means reaching the end of the function execution. 在这种情况下,退出范围意味着到达函数执行的结尾。 The reference comes into existence and goes back out of existence in the twinkling of an eye, without any effect on the larger world of objects and memory management. 转瞬之间,引用就存在了,而不再存在,对更大范围的对象和内存管理没有任何影响。

After the function executes, the only object still retaining the layer will be its superlayer ( self.layer.addSublayer ) — and if you had not assigned the layer to another layer as its sublayer, it would have vanished in a puff of smoke (a really tiny puff of smoke), because no one would have been retaining it. 函数执行后,唯一保留该层的对象将是其上层( self.layer.addSublayer )—如果您尚未将该层分配给另一层作为其子层,则该层将消失在烟雾中(a真的很小的烟雾),因为没有人会保留它。

In general, you are way overthinking this. 总的来说,您对此太想了。 The only time you ever need to worry about memory management in Swift is when a reference is persistent in some way. 您唯一需要担心Swift中的内存管理的时候就是引用以某种方式持久化的时候。 The typical (but not the only) example is an instance property. 典型的(但不是唯一的)示例是实例属性。

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

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