我创建了一个导航,它推送一个包含 ImageView 的 View Controller 和一个按钮,每次点击按钮时都会添加相同的 View Controller 。每次点击后,内存都会增长,并且每次后点击后,尽管调用了 deinit,但内存也不会释放。代码中没有任何内容表明内存泄漏,我是否缺少某些内容,谢谢?
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
最佳答案
最后,我找到了问题所在,问题出在导航栏上:
navigationController?.setNavigationBarHidden(true, animated: false)
此代码将消除大内存残留的所有问题。代码的其他部分都很好。在这种情况下,所有内存将始终保持在19M左右。
我尝试使用navigationDelegate进行转换,发现系统忽略了一个崩溃,并指出如果重复push vc将使NavigationBar布局不好。所以我把它隐藏起来,问题就消失了。但如果您确实需要navigationBar或其动画,那么这里需要做很多工作。
但是已经发现内存问题了。
关于swift - 导航 Controller 未释放内存,内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55387116/