demirb demirb - 5 months ago 24
Swift Question

UIView holds a strong reference

I have such a code

let view = UIView(x: x, y: y, w: sideSize, h: sideSize)
view.addTapGesture(action: { [weak self] (UITapGestureRecognizer) -> () in
view.reversePop()
})

extension UIView {
public func reversePop() {
// nothing here
}
}


When I use instruments I see that the ram usage increases, hence it doesn't release memory. When I comment out button.reversePop() the ram usage doesn't increase.

What can I do to prevent memory leak?

Answer

In this closure you capturing view every time you tap. You need to use weak reference of UIView, so your code might look like

let view = UIView(x: x, y: y, w: sideSize, h: sideSize)
view.addTapGesture(action: { [weak view] (UITapGestureRecognizer) -> () in
    view.reversePop()
})

extension UIView {
    public func reversePop() {
        // nothing here
    }
}

So, instead of [weak self], you need to use [weak view], because you are not calling self inside closure, no needs to weakify self.