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

复制代码
相关推荐
杭城小刘21 小时前
Weex 底层原理与 APM
ios·前端框架·weex
2501_924064111 天前
2025年移动应用渗透测试流程方案及iOS安卓测试方法对比
android·ios
鼹鼠SDN2 天前
【保姆教程】iPhone、iPad上玩电脑游戏 异地串流
ios·iphone·ipad·moonlight·sunshine·串流·科技数码
初级代码游戏2 天前
iOS开发 SwiftUI 2 : Image
ios·swiftui·swift
TheNextByte12 天前
如何在不使用 iCloud 的情况下备份 iPhone 短信
ios·iphone·icloud
denggun123452 天前
内存优化-(二)-oc&swift
ios·性能优化·cocoa·内存·swift
我要用代码向我喜欢的女孩表白2 天前
对象存储路径文件1TB以上文件比对,go语言
ios·golang·xcode
2501_916007472 天前
iPhone APP 性能测试怎么做,除了Instruments还有什么工具?
android·ios·小程序·https·uni-app·iphone·webview
2501_915106322 天前
Windows 环境下有哪些可用的 iOS 上架工具, iOS 上架工具的使用方式
android·ios·小程序·https·uni-app·iphone·webview
Student_Zhang2 天前
一个管理项目中所有弹窗的弹窗管理器(PopupManager)
前端·ios·github