ios - 如何取消初始化子 UIViewController?

标签 ios swift uiviewcontroller automatic-ref-counting deinit

我有几个添加到内容 View 中的UIViewController。调用我的删除函数后,我注意到子 UIViewControllerdeinit 函数不会被调用,除非我显式设置子 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/

相关文章:

swift - 如何使用 swift 处理 JSON 中丢失的对象?

ios - 仅在顶部停止过度滚动 UITableView?

ios - 尝试在已经呈现 UIAlertController 的 ViewController 上呈现 UIViewController

iOS 导航栏背景色

swift - Shinobi donut chart 表标签颜色不会改变

ios - 如何使用 siri-kit iOS10 调用 voip 电话

iphone - 如何防止 iOS 上的格式字符串攻击和缓冲区溢出?

ios - 为什么数字键盘会这样做(iOS 9)?

ios - Swift 3 - 异步作业后关闭 View Controller

ios - 为什么我必须清理并重新启动项目才能使用 Firebase/Crash 脚本文件运行项目