如何停止UIView容器UIViewController中的内存泄漏

时间:2019-04-01 19:00:35

标签: swift xcode memory-leaks uiviewcontroller heap-memory

我的手机内存有问题。我试图做类似android Fragments的事情,所以我有一个容器视图,当我需要更改视图时,我只在容器中设置了UIViewController,但是每次更改容器视图时,内存堆都会增加很多,所以8次单击后,iPhone上的内存将达到640mb。如何删除内存中的viewControllers? 这是我的代码:

 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 {

    }
}

1 个答案:

答案 0 :(得分:0)

您当前的代码看起来不错,请检查MapContainerViewControllerNotificationsContainerViewController中是否存在保留周期。 我建议您检查在视图控制器中定义的所有闭包和变量。