简体   繁体   中英

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:

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.

Do I need to declare the "border" -- the CAShapeLayer -- as weak? Or will that go out of scope once the function executes, leaving the only reference to the object being the one from the 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.

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. The typical (but not the only) example is an instance property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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