Swift的NSClassFromString转换

在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

复制代码
相关推荐
Digitally36 分钟前
如何在iPhone上共享日历
ios·iphone
库奇噜啦呼3 小时前
【iOS】多线程学习
macos·ios·cocoa
xiAo_Ju5 小时前
iOS一个Fancy UI的Tricky实现
前端·ios
游戏开发爱好者85 小时前
iOS 商店上架全流程解析 从工程准备到审核通过的系统化实践指南
android·macos·ios·小程序·uni-app·cocoa·iphone
QuantumLeap丶7 小时前
《Flutter全栈开发实战指南:从零到高级》- 18 -自定义绘制与画布
android·flutter·ios
玲珑Felone13 小时前
flutter 状态管理--InheritedWidget、Provider原理解析
android·flutter·ios
AskHarries15 小时前
中国身份证注册美区 Apple Developer 个人账号完整教程
ios·apple
2501_9160088917 小时前
Objective-C 测试(OC 测试)指南 从单元测试到性能调优的多工具协同方法
android·ios·小程序·https·uni-app·iphone·webview
PJHubs1 天前
把一年前写给自己用的翻译软件开源了 | TranslateP
ios·产品