首页 > 解决方案 > 如何在 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 {

    }
}

标签: swiftxcodememory-leaksuiviewcontrollerheap-memory

解决方案


MapContainerViewController您当前的代码看起来不错,请检查or中是否有保留循环NotificationsContainerViewController。我建议您检查视图控制器中定义的所有闭包和变量。


推荐阅读