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

复制代码
相关推荐
WeiAreYoung2 小时前
uni-app Xcode制作iOS谷歌广告Google Mobile Ads SDK插件
ios·uni-app
2501_916008892 小时前
iOS 开发助手工具,设备信息查看、运行日志、文件管理等方面
android·ios·小程序·https·uni-app·iphone·webview
编程之路从0到13 小时前
React Native新架构之iOS端初始化源码分析
react native·ios·源码剖析·新架构·初始化流程
2501_915921433 小时前
在没有源码的前提下,怎么对 Swift 做混淆,IPA 混淆
android·开发语言·ios·小程序·uni-app·iphone·swift
00后程序员张17 小时前
对比 Ipa Guard 与 Swift Shield 在 iOS 应用安全处理中的使用差异
android·开发语言·ios·小程序·uni-app·iphone·swift
00后程序员张21 小时前
在 iOS 设备上同时监控 CPU、GPU 与内存的方法
android·ios·小程序·https·uni-app·iphone·webview
TheNextByte11 天前
如何从锁定的 iPhone 中恢复照片?
ios·iphone
Maynor9961 天前
Clawdbot手机访问完整教程:像用App一样方便
ios·智能手机·iphone
游戏开发爱好者81 天前
在 Windows、Linux 与 CI 环境下命令行上传 IPA 到 App Store
linux·windows·ios·ci/cd·小程序·uni-app·iphone
符哥20081 天前
对比ArkTsUI和Flutter和 SwiftUI 和Jetpack Compose四个框架语法及使用场景。
flutter·ios·swiftui