从Swift中的string和Pass参数获取类

时间:2018-04-20 11:03:05

标签: ios swift

我在objective-c中有一个方法,它接受字符串并转换为类并将一些公共对象传递给它。

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

现在同样的事情转变为迅捷。

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()
}

这里的问题是无法传递所有视图控制器中存在的公共对象。我想像在objective-c中那样传递apprenderer对象。

1 个答案:

答案 0 :(得分:1)

我建议你为你所有的ViewControllers创建一个基类,

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")
    }
}

然后你可以从服务器返回的类名实例化,如下所示,

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
}