我的个人工具箱库中有以下扩展:
public extension UIViewController {
public func removeChildViewControllers() {
for child in self.childViewControllers {
child.willMove(toParentViewController: nil)
child.view.removeFromSuperview()
child.removeFromParentViewController()
}
}
public func addChildViewController(_ controller: UIViewController, embedViewIn containerView: UIView) {
controller.willMove(toParentViewController: self)
addChildViewController(controller)
containerView.addSubview(controller.view)
controller.view.addCustomConstraints(CustomConstrains.FullSizeInSuperview)
controller.didMove(toParentViewController: self)
}
}
在我当前的应用中,我调用如下:
private func embedViewController(_ controller: UIViewController) {
removeChildViewControllers()
addChildViewController(controller, embedViewIn: containerView)
}
一切都按预期工作。
现在我再添加一个方便的方法removeChildViewController
:
public extension UIViewController {
public func removeChildViewControllers() {
for child in self.childViewControllers {
child.willMove(toParentViewController: nil)
child.view.removeFromSuperview()
child.removeFromParentViewController()
}
}
public func addChildViewController(_ controller: UIViewController, embedViewIn containerView: UIView) {
controller.willMove(toParentViewController: self)
addChildViewController(controller)
containerView.addSubview(controller.view)
controller.view.addCustomConstraints(CustomConstrains.FullSizeInSuperview)
controller.didMove(toParentViewController: self)
}
public func removeChildViewController(_ controller: UIViewController) {
controller.willMove(toParentViewController: nil)
controller.view.removeFromSuperview()
controller.removeFromParentViewController()
}
}
从现在开始,调用未修改的代码会在运行时崩溃 EXC_BAD_ACCESS:
removeChildViewControllers()
总结一下:
如果(未使用的)方法 removeChildViewController
存在,则调用 removeChildViewControllers()
会在运行时崩溃。
如果注释了(未使用的)方法 removeChildViewController
,调用 removeChildViewControllers()
不会在运行时崩溃。
此外,如果(未使用的)方法 removeChildViewController
重命名为 removeChildViewControllerr
,调用 removeChildViewControllers()
不会在运行时崩溃。
最佳答案
我猜这是您遇到 secret namespace 冲突的情况之一。在 Objective-C Cocoa 世界中可能 隐藏了一个 removeChildViewController
方法,而您通过重复它的名称无意中发现了它。因此,Objective-C Cocoa 在运行时会卡住,即使官方 API 没有问题,因此让 Swift 编译您的代码也没有问题。不幸的是,这种事情经常发生。
关于ios - 运行时找不到方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40493497/