Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do I need to remove UIGestureRecognizer in deinit?

Tags:

ios

swift

I have custom view, which contains UILabel and I add gesture recognizer to this label in init.

protocol CustomViewDelegate: class {
    func customViewDidTapOnLabel(_ customView)
}

class CustomView: UIView {

    lazy var label = UILabel()

    weak var delegate: CustomViewDelegate?

    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(label)
        label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(labelTapped))
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @objc func labelTapped() {
        delegate?.customViewDidTapOnLabel(self)
    }
}

The question is, should I remove gesture recognizer in deinit? Does the label keep strong reference do UITapGestureRecognizer?

like image 922
Nominalista Avatar asked Dec 23 '22 12:12

Nominalista


1 Answers

The view owns the gesture recognizer. The superview owns the view. When your view controller's view goes out of memory, it no longer retains its supviews, which are then released (assuming nothing else is holding them). Similarly when the label is released it releases its gesture recognizers. So no you don't need to manually remove it.

But why take my word for it? You can assign your gesture recognizer to a weak global reference. Check the reference after the viewcontroller has been released and you will see that the reference is indeed nil if the only thing referencing it was a subview of the view controller.

like image 173
Josh Homann Avatar answered Jan 02 '23 10:01

Josh Homann