Swift

Swift 中使用 NSClassFromString时遇到的坑

2017-11-28  本文已影响19人  izsm
问题:

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)
上一篇 下一篇

猜你喜欢

热点阅读