【问题标题】:How to stop memory leak in UIView Container UIViewController如何在 UIView Container UIViewController 中停止内存泄漏
【发布时间】:2019-04-01 19:00:35
【问题描述】:

我的手机内存有问题。我正在尝试做类似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 {

    }
}

【问题讨论】:

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 2014-04-19
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    相关资源
    最近更新 更多