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_915921432 小时前
iOS 应用上架多环境实战,Windows、Linux 与 Mac 的不同路径
android·ios·小程序·https·uni-app·iphone·webview
Cyclic10016 小时前
IOS购买订阅通知信息解析说明Java
java·开发语言·ios
00后程序员张6 小时前
iOS 应用上架常见问题与解决方案,多工具组合的实战经验
android·ios·小程序·https·uni-app·iphone·webview
2501_916007471 天前
iOS App 上架实战 从内测到应用商店发布的全周期流程解析
android·ios·小程序·https·uni-app·iphone·webview
wjm0410061 天前
ios八股文 -- Objective-c
开发语言·ios·objective-c
麦兜*2 天前
Swift + Xcode 开发环境搭建终极指南
开发语言·ios·swiftui·xcode·swift·苹果vision pro·swift5.6.3
Digitally2 天前
重置iPhone会删除所有内容吗? 详细回答
ios·iphone
普罗米拉稀2 天前
Flutter 复用艺术:Mixin 与 Abstract 的架构哲学与线性化解密
flutter·ios·面试
kymjs张涛2 天前
零一开源|前沿技术周刊 #12
ios·google·github
2501_915918413 天前
iOS 应用上架全流程实践,从开发内测到正式发布的多工具组合方案
android·ios·小程序·https·uni-app·iphone·webview