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

复制代码
相关推荐
Data_Journal5 小时前
Golang 中解析 HTML 的指南
ios·iphone
jike_20269 小时前
销售拜访记录APP推荐:客户沟通内容怎么快速整理?
ios·语音识别·iphone
00后程序员张11 小时前
iOS 开发全流程需要哪些工具?编码、调试、构建、发布阶段选择
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
游戏开发爱好者81 天前
WebSocket 抓包怎么查看内容?从握手到消息帧完整解读
网络协议·计算机网络·网络安全·ios·adb·https·udp
悟空瞎说1 天前
# Alamofire 使用文档 完整翻译
ios
WeiAreYoung1 天前
Flutter+iOS 实现 Live Activity
flutter·ios
2501_916008891 天前
Swift多环境配置:利用Scheme实现灵活的多环境管理
开发语言·ide·vscode·ios·个人开发·swift·敏捷流程
00后程序员张1 天前
Windows / Linux / Mac 上不用 Xcode 把 IPA 上传到 App Store,upload 命令详解
android·ios·小程序·https·uni-app·iphone·webview
秦少游在淮海1 天前
id - Android、iOS
android·ios