問題:
unexpectedly found nil while unwrapping an Optinal value
代碼:
let classDic = dataSource![indexPath.row]
let className: String = classDic["class"] as! String
let cls = NSClassFromString(className) as! UIViewController.Type
let vc: UIViewController = cls.init()
navigationController?.pushViewController(vc, animated: true)
執行的時候會崩在這里:
let cls = NSClassFromString(className) as! UIViewController.Type
我們自定義的類明明已經存在,為什么在展開的時候卻找不到,發現為空?
swift跟OC的差別還是蠻大的,由字符串轉為類型的時候 如果類型是自定義的 需要在類型字符串前邊加上你的項目的名字
解決辦法:
定義一個返回app名稱的方法
func getAPPName() -> String {
let nameKey = "CFBundleName"
let appName = Bundle.main.object(forInfoDictionaryKey: nameKey) as? String
return appName!
}
設置類名字:
let cls = NSClassFromString(getAPPName() + "." + className) as! UIViewController.Type
注意:中間別忘了加點 "."
最終代碼:
let classDic = dataSource![indexPath.row]
let className:String = classDic["class"] as! String
let cls = NSClassFromString(getAPPName() + "." + className) as! UIViewController.Type
let vc: UIViewController = cls.init()
navigationController?.pushViewController(vc, animated: true)