swift - 如何在 UIView Container UIViewController 中停止内存泄漏
问题描述
我的手机内存有问题。我正在尝试做类似android Fragments的事情,所以我有一个容器视图,当我需要更改视图时,我只在容器中设置了UIViewController,但是每次更改容器视图时,内存堆都会增加很多,所以在 8 次点击中,iPhone 上的内存达到 640mb。如何删除内存中的视图控制器?这是我的代码:
private var activeViewController : UIViewController?{
didSet {
removeInactiveViewController(inactiveViewController:oldValue)
updateActiveViewController()
}
}
private func removeInactiveViewController(inactiveViewController: UIViewController?){
if let inactiveVC = inactiveViewController {
inactiveVC.willMove(toParent: nil)
inactiveVC.view.removeFromSuperview()
view controller
inactiveVC.removeFromParent()
}
}
private func updateActiveViewController(){
if let activeVC = activeViewController {
var duration = 0
addChild(activeVC)
activeVC.view.frame = fragmentContainer.bounds
fragmentContainer.addSubview(activeVC.view)
activeVC.didMove(toParent: self)
}
}
@IBAction func clickSearchs(_ sender: Any) {
if (statusFragments != 1 && statusFragments != 0){
prevStatusFragments = statusFragments
statusFragments = 1
imgSearch.isSelected = true
imgNotif.isSelected = false
imgRecord.isSelected = false
imgProfile.isSelected = false
imgOptions.isSelected = false
if (mapViewController != nil) {
print("Ya existia")
mapViewController!.removeFromParent()
mapViewController = nil
}
mapViewController = storyboard!.instantiateViewController(withIdentifier:
"MapContainerViewController")
activeViewController = mapViewController
} else {
}
}
@IBAction func clickNotifs(_ sender: Any) {
print("Hizo click en notificaciones")
if (statusFragments != 2){
prevStatusFragments = statusFragments
statusFragments = 2
imgSearch.isSelected = false
imgNotif.isSelected = true
imgRecord.isSelected = false
imgProfile.isSelected = false
imgOptions.isSelected = false
if (notifViewController != nil) {
notifViewController!.removeFromParent()
notifViewController!.removeFromParent()
notifViewController = nil
}
notifViewController = storyboard!.instantiateViewController(withIdentifier: "NotificationsContainerViewController")
activeViewController = notifViewController
} else {
}
}
解决方案
MapContainerViewController
您当前的代码看起来不错,请检查or中是否有保留循环NotificationsContainerViewController
。我建议您检查视图控制器中定义的所有闭包和变量。
推荐阅读
- angular - 如何测试方法的返回值 [Jasmine]
- powershell - 通过 PowerShell 向组授予 SharePoint Online 文件夹权限
- python - 如何使用列表理解并在每次字符串包含单词时放置 1
- c++ - 具有外部定义的默认特殊成员函数
- c - C中代码的错误功能。程序似乎显示垃圾
- winapi - Winapi - 如何为 MS Edge 浏览器实现等效的 LWA_COLORKEY
- python - cython: Cythonizing 一个大的字典查找
- typescript - d3 和打字稿。selection.merge 类型问题
- python - 在 django 2.2 的另一个视图中调用 DRF api
- cordova - Cordova 版本不变