demiculus
demiculus

Reputation: 1343

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?

Upvotes: 2

Views: 279

Answers (1)

Pavel Gatilov
Pavel Gatilov

Reputation: 2590

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.

Upvotes: 4

Related Questions