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

复制代码
相关推荐
2501_915909062 小时前
原生 iOS 开发全流程实战,Swift 技术栈、工程结构、自动化上传与上架发布指南
android·ios·小程序·uni-app·自动化·iphone·swift
2501_915106322 小时前
Comodo HTTPS 在工程中的部署与排查实战(证书链、兼容性与真机抓包策略)
网络协议·http·ios·小程序·https·uni-app·iphone
2501_915909062 小时前
苹果软件混淆与 iOS 代码加固趋势,IPA 加密、应用防反编译与无源码保护的工程化演进
android·ios·小程序·https·uni-app·iphone·webview
2501_916007472 小时前
苹果软件混淆与 iOS 应用加固实录,从被逆向到 IPA 文件防反编译与无源码混淆解决方案
android·ios·小程序·https·uni-app·iphone·webview
Zender Han7 小时前
Flutter 实现人脸检测 — 使用 google_mlkit_face_detection
android·flutter·ios
2501_916008898 小时前
iOS 26 性能分析深度指南 包含帧率、渲染、资源瓶颈与 KeyMob 协助策略
android·macos·ios·小程序·uni-app·cocoa·iphone
Mr_zheng13 小时前
iOS 26 UIKit和Swift上的更新
ios·swift
YungFan13 小时前
iOS26适配指南之UISearchController
ios·swift
陈彬技术实践14 小时前
从 Auto Layout 原理看:为什么 UITableView.tableHeaderView 无法自动撑开?
ios
2501_9159090621 小时前
tcpdump 抓包数据分析实战,命令、过滤、常见故障定位与真机补充流程
网络·测试工具·ios·小程序·uni-app·iphone·tcpdump