iOS:ViewController通过引用保存

时间:2019-05-28 08:22:35

标签: ios swift memory-management automatic-ref-counting

我有一个Viewcontroller A,在其中我将动态添加的其他ViewController的视图添加到A的subView中。出于效率原因,我将这些视图控制器保留在字典中,并动态删除/添加其视图。

但是A被取消初始化,但其他视图控制器未初始化。我也在内存调试器中看到了这一点,但不知道如何解决此循环。

retain cycle

这是我在A里面的字典,其中包含所有子视图控制器:

private var subControllerMap = [String:UIViewController?]()

这里是我如何进行动态加载

 func addControllerWithIdentifierAndZoneId(_ identifier: String, storyboardNibName: String, containerView: UIView,zoneId: String?){
        containerView.subviews.first?.removeFromSuperview()
        let _ = children.map{$0.removeFromParent()}
        var ctrlr: UIViewController? = subControllerMap[identifier] as? UIViewController

        //only create a new controller if needed - otherwise use reference from map
        if ctrlr == nil{
            let storyboard = UIStoryboard(name: storyboardNibName, bundle: nil)
            ctrlr = storyboard.instantiateViewController(withIdentifier: identifier)
            subControllerMap[identifier] = ctrlr
        }
        guard let controller = ctrlr else{
            return
        }

        if let castedController  = controller as? BController {
            castedController.isInEditMode = true
        }else if let castedControler = controller as? CController{
            castedControler.isInEditMode = false
        }else if let castedController = controller as? DController{
            castedController.isInEditMode = true
        }

        controller.view.translatesAutoresizingMaskIntoConstraints = false
        addChild(controller)
        addSubview(subView: controller.view, toView: containerView)
        controller.didMove(toParent: self)
    }

如果我点击分段控件上的分段,则会调用此函数。例如

addControllerWithIdentifierAndZoneId("BController", storyboardNibName: "Room", containerView: containerView,zoneId: zoneId)

我试图在vieDidDisappear中进行清理,但这没有帮助

override func viewDidDisappear(_ animated: Bool) {
    super.viewDidDisappear(animated)

    subControllerMap.values.forEach { (controller) in
        controller?.view.removeFromSuperview()
        controller?.removeFromParent()
    }
    subControllerMap.removeAll()
    containerView.subviews.forEach { (view) in
        view.removeFromSuperview()
    }
    containerView.removeFromSuperview()

}

0 个答案:

没有答案