0

I have a method in objective-c which takes string and converting to class and passing some common object to it.

-(UIViewController*)getUIViewController{
 NSString* templateID = @"templateId"; // This value is coming from ba ckend
Class c = NSClassFromString(templateID);
UIViewController* vc = [[c alloc] initWithAppRender:appRenderer];
return vc;
}

Now the same thing converting to swift.

func getUIViewController() -> UIViewController? {
    let templateID = "templateId"
    let className = Bundle.main.infoDictionary!["CFBundleName"] as! String + "." + templateID
    let aClass = NSClassFromString(className) as! UIViewController.Type
    return aClass.init()
}

Here the problem is not able to pass common object which exists in all view controllers. I want to pass apprenderer object like in objective-c.

11
  • do you have a base controller for all your ViewController? Commented Apr 20, 2018 at 11:29
  • You would need to extend UIViewController to have an additional convenience init that accepts an appRenderer Commented Apr 20, 2018 at 11:32
  • @Kamran I don't have a base controller Commented Apr 20, 2018 at 11:34
  • @Paulw11 Even though i have convenience init. I need to warp the view controller from class object. I want to pass with out wrapping Commented Apr 20, 2018 at 11:36
  • Instantiating a class from Type can be done with required initializer but as we can not add a required initializer in extension so seems impossible by extending UIViewController. Can you share obj-c code of initWithAppRender where it is defined, It might be helpful to find some solution? Commented Apr 20, 2018 at 11:44

1 Answer 1

1

I would suggest you to create a base class for all your ViewControllers like this,

class BaseViewController: UIViewController {

    private var render: NSObject?

    required init(appRenderer: NSObject?) {
        super.init(nibName: nil, bundle: nil)

        self.render = appRenderer
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

And then you can instantiate from the server returned class name as below,

func getUIViewController() -> UIViewController? {
    let templateID = "templateId"
    let className = Bundle.main.infoDictionary!["CFBundleName"] as! String + "." + templateID
    let aClass = NSClassFromString(className) as! BaseViewController.Type
    let vc = aClass.init(appRenderer: nil)
    return vc
}
Sign up to request clarification or add additional context in comments.

1 Comment

can u please suggest how to load view from storyboard in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.