在swift 中使用NSClassFromString 从string 转换到 对象,报了Segmentation fault: 11 错误。
Swift
let ctrlClass: AnyClass = NSClassFromString("HomeViewController")!
let ctrl: UIViewController = ctrlClass.init() as UIViewController
正确的写法:
Swift
let bundleName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String
let ctrlClass = NSClassFromString(bundleName+".HomeViewController") as! UIViewController.Type;
let ctrl: UIViewController = ctrlClass.init()
NSClassFromString 在Swift中的参数不只是一个单独的类名,而是一个完整的包名加类名组成的字符串,否则会报错:
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value