NSClassFromString在OC中运行良好,但在Swift

时间:2016-08-15 04:10:20

标签: ios objective-c swift

在OC中工作正常:

NSString *controllerName = @"SecondViewController";
Class clazz = NSClassFromString(controllerName);
UIViewController *viewController = [[clazz alloc] init];
[self.navigationController pushViewController:viewController animated:YES];

当我使用swift时:

let controllerName = "SecondViewController"
let controller:AnyClass = NSClassFromString(controllerName)!
let viewController = (controller as! UIViewController.Type).init()
navigationController?.pushViewController(viewController, animated: true)

它在let controller:AnyClass = NSClassFromString(controllerName)!

坠毁

有什么想法吗?

enter image description here

1 个答案:

答案 0 :(得分:1)

Swift类现在是命名空间,而不是" SecondViewController"它" AppName.SecondViewController"

    let nameSpace = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as! String
    let controllerName = "SecondViewController"
    let controller:AnyClass = NSClassFromString(nameSpace + "." + controllerName)!
    let viewController = (controller as! UIViewController.Type).init()
    navigationController?.pushViewController(viewController, animated: true)