Tony
Tony

Reputation: 542

NSClassFromString works well in OC, but crashes in Swift

It works fine in OC:

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

When I use swift:

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

It crashed at let controller:AnyClass = NSClassFromString(controllerName)!

Any ideas?

enter image description here

Upvotes: 0

Views: 386

Answers (1)

Tony
Tony

Reputation: 542

Swift classes are namespaced now so instead of "SecondViewController" it'd be "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)

Upvotes: 1

Related Questions