我需要知道如何在标签栏控制器项目中从视图控制器中释放/释放内存,deinit方法不会调用这两个视图控制器。我使用仪器工具,它告诉我它在内存中,而不是释放它
下面是我为这两个视图控制器编写的代码。点击应用程序中的第一个视图控制器是:
import UIKit
class WebViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
print("web view controller is De init")
}
override func viewWillDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.dismiss(animated: true, completion: nil)
}
}在被点击的应用程序中,同一项目中的第二个视图控制器如下:
import UIKit
class MovieDownloadingViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.dismiss(animated: true, completion: nil)
}
deinit {
print("Movie Downloading View Controller is De init")
}
}您可以尝试该代码,并看到deinit方法未调用
请问什么时候是强引用,错误的代码泄漏了内存,所以它不能从这些视图控制器释放内存?
发布于 2017-02-27 18:21:58
我的解决方案是从viewWillDisappear()中获取视图控制器的引用
let sb = UIStoryboard(name: "Main", bundle: nil)
var vc = sb.instantiateViewController(withIdentifier: "Web") as? WebViewController
if vc != nil {
vc = nil
}并将其设置为nil,以便调用deinit
发布于 2017-02-28 02:14:02
如果您希望在选择选项卡时释放视图控制器,则不应使用选项卡栏控制器,而应使用自己的选项卡栏控制器(使用选项卡视图,并在选择选项卡时执行视图控制器包含调用以添加和删除子视图控制器)。
但更深层次的问题是,你为什么要经历所有这些?视图控制器使用的内存量可以忽略不计。如果您正在尝试解决内存问题,请找出占用大量内存的原因,然后在viewDidDisappear中只释放内存,而不释放视图控制器。
发布于 2017-02-27 16:02:14
因为视图控制器是由选项卡栏视图控制器呈现的,所以选项卡栏视图控制器将持有对它们的引用,直到它被释放为止。
您可以尝试将选项卡栏视图控制器替换为其他东西,以查看您的视图控制器将被释放。
UIApplication.shared.delegate?.window?.rootViewController = UIViewController()在执行上面的代码行之后,您的两个deinit都应该被调用。
https://stackoverflow.com/questions/42480355
复制相似问题