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

复制代码
相关推荐
1024小神12 小时前
swift中使用ObservableObject单利模式的时候,用let 或 @ObservedObject 或 @StateObject 有什么区别
开发语言·ios·swift
如此风景13 小时前
SwiftUI 状态管理详解
ios
QuantumLeap丶13 小时前
《Flutter全栈开发实战指南:从零到高级》- 25 -性能优化
android·flutter·ios
游戏开发爱好者817 小时前
H5 混合应用加密 Web 资源暴露到 IPA 层防护的完整技术方案
android·前端·ios·小程序·uni-app·iphone·webview
2501_9151063218 小时前
最新版本iOS系统设备管理功能全面指南
android·macos·ios·小程序·uni-app·cocoa·iphone
游戏开发爱好者818 小时前
HTTPS DDoS 排查 异常流量到抓包分析
网络协议·ios·小程序·https·uni-app·iphone·ddos
TouchWorld18 小时前
iOS逆向-哔哩哔哩增加3倍速播放(3)-[横屏视频-全屏播放]场景
ios·swift
2501_9159184119 小时前
iOS 性能监控 运行时指标与系统行为的多工具协同方案
android·macos·ios·小程序·uni-app·cocoa·iphone
00后程序员张19 小时前
IPA 混淆技术全解,从成品包结构出发的 iOS 应用安全实践与工具组合
android·安全·ios·小程序·uni-app·cocoa·iphone