问题:
found nil while unwrapping an Optinal value
代码:
if let cls = NSClassFromString("TestViewController") as? UIViewController.Type {
let vc = cls.init()
navigationController?.pushViewController(vc, animated: true)
}
然而执行的时候并没有进入if判断里面。
我们自定义的类明明已经存在,为什么在展开的时候却找不到,发现为空
swift跟OC的差别还是蛮大的,由字符串转为类型的时候 如果类型是自定义的 需要在类型字符串前边加上你的项目的名字
解决办法:
定义一个返回app名称的方法
func getAPPName() -> String {
guard let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String else { return "" }
return appName
}
然后这样就可以了:
if let cls = NSClassFromString(getAPPName() + "." + "TestViewController") as? UIViewController.Type {
let vc = cls.init()
navigationController?.pushViewController(vc, animated: true)
}
注意:中间别忘了加点 "."