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

复制代码
相关推荐
笑尘pyrotechnic11 小时前
LLDB进阶:使用命令行进行检查
ios·objective-c·cocoa·lldb
z***y86213 小时前
Swift在iOS中的Xcode
ios·xcode·swift
AirDroid_cn13 小时前
iOS 18 后台应用偷跑流量,如何限制?
macos·ios·cocoa
明君8799716 小时前
Flutter 图纸标注功能的实现:踩坑与架构设计
android·ios
江东小bug王17 小时前
深入理解 UINavigationController:生命周期、动画优化与性能调优
ios
Lexiaoyao2018 小时前
Apple StoreKit 2 开发指南
ios·apple
2501_915106321 天前
iOS App 测试工具全景分析,构建从开发调试到线上监控的多阶段工具链体系
android·测试工具·ios·小程序·uni-app·iphone·webview
Digitally2 天前
如何通过蓝牙将联系人从 iPhone 传输到 Android
android·ios·iphone
90后的晨仔2 天前
2025年11月27日年解决隐私清单导致审核总是提示二进制无效的问题
ios
songgeb2 天前
iOS Audio后台模式下能否执行非Audio逻辑
ios·swift