我有几个添加到内容 View 中的UIViewController
。调用我的删除函数后,我注意到子 UIViewController
的 deinit
函数不会被调用,除非我显式设置子 UIViewController< 的值
到 nil
。
这是正确的行为还是我做错了什么?
func removeViewController(fromCell cell:UICollectionViewCell, at indexPath:IndexPath){
guard let childViewController = currentViewControllers[indexPath] else { return }
print("remove view controller called")
childViewController.willMove(toParent: nil)
childViewController.view.removeFromSuperview()
childViewController.removeFromParent()
currentViewControllers[indexPath] = nil
// recycledViewControllers.insert(childViewController)
}
最佳答案
问题是您有两个对 subview Controller 的引用:
由父 View Controller 自动维护的引用(
childViewControllers
,或现代 Swift 中的children
)您自己添加的附加引用 (
currentViewControllers
)。
因此,在 subview Controller 消失之前,您必须让它们都消失。这就是您的代码的作用:
childViewController.willMove(toParent: nil)
childViewController.view.removeFromSuperview()
childViewController.removeFromParent()
// now `childViewControllers` / `children` has let go
currentViewControllers[indexPath] = nil
// now `currentViewController` has let go
因此,您本身没有做任何错误,除非您首先通过使用此 currentViewControllers
添加了此额外的强引用。但我明白你为什么这样做:你想要一种将索引路径与 subview Controller 配对的方法。
因此,您可以很好地接受您的方法,或者如果您确实愿意,您可以将 currentViewControllers
配置为仅对其值进行弱引用(通过使用 NSMapTable 代替字典)。
关于ios - 如何取消初始化子 UIViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55907469/