0

I have a class type String which return from WebService called MainViewController and I want to get a class object from it. It always fails.

This is my code:

    let classStringFromWS = "MainViewController"
    if let viewControllerString = NSClassFromString(classStringFromWS) as? UIViewController.Type {
        let viewController = viewControllerString.init(nibName: classStringFromWS, bundle: nil)
        self.navigationController?.pushViewController(viewController, animated: true)
    }
ytpm
  • 4,962
  • 6
  • 56
  • 113

1 Answers1

0

Here is possible solution. Tested with Xcode 11.4.

Use factory function (anyway to create instance of class, the class must be available, so) assuming it is available in same module

func createInstance(for className: String) -> UIViewController? {
    // registry of supported controllers
    let classRegistry: [String: UIViewController.Type] = [
        "MainViewController": MainViewController.self
        // other supported controllers here
    ]

    if let aClass = classRegistry[className] {
        return aClass.init(nibName: className, bundle: nil)
    }
    return nil
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • @YossiTsafar, even if you get class name from WS, the class itself must be present in run-time. So where it is? Where did you declare it (ie. `class MainViewController: UIViewController {...}`? – Asperi May 04 '20 at 15:34