UIControl内存泄漏

时间:2019-01-19 22:55:50

标签: ios swift memory-leaks uicontrol

我通常像下面的示例一样设置UIImageViewUITextField等。但是在下面的示例中我遇到了内存泄漏,我不确定为什么。

如果我使用标准设置

var buttonImageView: UIImageView!

并在泄漏消失的init方法中设置buttonImageView

OR

在下面的示例中,如果我将其设为lazy,则泄漏也会消失

示例

class BasicButton: UIControl {

    // Cause of leak
    var buttonImageView: UIImageView = {
        let logoView = UIImageView()
        logoView.contentMode = .scaleAspectFill
        logoView.tintColor = UIColor.blue
        logoView.translatesAutoresizingMaskIntoConstraints = false
        logoView.isUserInteractionEnabled = false
        return logoView
    }()

    init(image: UIImage) {
        self.init()
        buttonImageView.image = image
        setupView()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    private func setupView() {
        addSubview(buttonImageView)
        setupLayout()
    }

    private func setupLayout() {
        translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            buttonImageView.centerXAnchor.constraint(equalTo: centerXAnchor),
            buttonImageView.centerYAnchor.constraint(equalTo: centerYAnchor),
            buttonImageView.heightAnchor.constraint(equalToConstant: 80),
            buttonImageView.widthAnchor.constraint(equalToConstant: 80)
        ])
    }
}

1 个答案:

答案 0 :(得分:0)

结果是我没有打super。初始化UIControl的正确方法如下:

init(image: UIImage) {
    // Fixes Leak
    super.init(frame:CGRect(x: 0, y: 0, width: 100, height: 100))
    // Wrong init was called causing leak
    // self.init()

    buttonImageView.image = image
    setupView()
}

但是,代码仍然可以编译并运行,但是会导致进程泄漏。如果有人能详细说明为什么会发生这种情况,将不胜感激。