ios - 运行时找不到方法

标签 ios swift swift3

我的个人工具箱库中有以下扩展:

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/

相关文章:

ios - UISearchcontroller 取消按钮不起作用

ios - 如何找出哪个约束不起作用或产生问题

ios - 限制和缩放 UITextField 中文本的大小

ios - 无法在我的音乐播放器应用程序上播放音乐

ios - 无法在 iOS 开发人员中心创建分发配置文件

ios - iO 的 RDoc 是什么?

ios - Catalyst 的 ML 构建错误(Xcode 12 GM)

ios - urlSession :dataTask:didReceive:completionHandler not called in Xcode8 Swift3

ios - 使用选项卡栏 Controller Swift 在导航栏中添加新的栏按钮

objective-c - 从弱链接的 iOS 类或不在部署目标 iOS 版本中的类继承