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_9160074717 小时前
跨平台 App 安全,Flutter、RN、Unity、H5 混合应用加固
android·ios·小程序·https·uni-app·iphone·webview
新 一.17 小时前
uniapp在ios上真机测试运行
ios·uni-app
2501_9160074718 小时前
不越狱如何查看iOS 应用的详细信息及其文件目录结构
android·macos·ios·小程序·uni-app·cocoa·iphone
handsome091618 小时前
上传app store和IOS更新版本的实战流程
ios·打包上架
2501_9160088921 小时前
无需钥匙串快速创建 iOS 开发 / 发布证书 P12 CSR
android·ios·小程序·https·uni-app·iphone·webview
金山毒霸电脑医生2 天前
植物大战僵尸融合版下载与安装教程:PC/安卓/iOS 全面指南
游戏·ios·植物大战僵尸·植物大战僵尸融合版·游戏工具
金山毒霸电脑医生2 天前
植物大战僵尸杂交版最新v0.2版下载安装|2025图文解析教程
android·游戏·ios·植物大战僵尸·软件下载安装
恋猫de小郭2 天前
Android Gradle Plugin 9.0 发布,为什么这会是个史诗级大坑版本
android·flutter·ios·开源
keep the2 天前
Windows启动IOS17/18的WDA
windows·ios·自动化
weixin_403810132 天前
EasyClick iOS自动化代理IPA挂了 如何再次启动?
android·ios·自动化