导航控制器未释放内存,内存泄漏?

时间:2019-03-27 21:59:13

标签: swift xcode memory-leaks uinavigationcontroller automatic-ref-counting

我创建了一个导航,该导航会推送一个包含图像视图的视图控制器,以及一个按钮,该按钮每次单击都会添加相同的视图控制器。每次轻击后,内存都会增加,而每次后轻击后,尽管调用了deinit,但不会释放内存。代码中没有指向内存泄漏的内容,是我缺少的东西吗?

complete project repository

class ViewController: UIViewController {


     lazy var nextButton:UIButton? = {
        let button = UIButton(type: .roundedRect)
        button.setTitle("Next", for: .normal)
        button.addTarget(self, action: #selector(nextButtonTapped), for: .touchUpInside)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = UIColor.red
        return button
    }()

     lazy var imageView:UIImageView? = {
        let image = #imageLiteral(resourceName: "DJI_0014")
        let imageView = UIImageView(image: image)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        guard let imageView = self.imageView, let nextButton = self.nextButton else{
            print("imageView, nextButton are nil")
            return
        }

        self.view.backgroundColor = UIColor.white

        self.view.addSubview(imageView)
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo:self.view.topAnchor),
            imageView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            imageView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
            imageView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)])

        view.addSubview(nextButton)
        NSLayoutConstraint.activate([nextButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
            nextButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor, constant: 0),nextButton.heightAnchor.constraint(equalToConstant: 200),nextButton.widthAnchor.constraint(equalToConstant: 200)])
    }

    @objc func nextButtonTapped(){
        print("next button tapped")
        self.navigationController?.pushViewController(ViewController(), animated: true)
    }

    deinit {
        print("view controller is deinitialized")
    }

}

我查看了下面列出的其他问题,并试图采纳他们的建议,但似乎没有一个帮助

Navigation arc memory not released

Memory leak issue in navigation controller

Memory Degbugger

1 个答案:

答案 0 :(得分:0)

最后,我已经确定了问题所在,这是从navigationBar引起的:

` navigationController?.setNavigationBarHidden(true, animated: false)`

此代码将消除所有有关大内存残留的问题。代码的其他部分也可以。在这种情况下,所有内存将始终保持1900万左右。

我试图使用navigationDelegate进行转换,发现系统崩溃了,并且崩溃了,并认为如果重复执行推vc会使NavigationBar布局不正确。因此我将其隐藏起来,问题就消失了。但是,如果您确实需要navigationBar或其动画,那么这里将有很多工作要做。

但是发现了内存问题。