本文主要是介绍[Swift]获取对象的类名和使用类名创建对象,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在UITabBarController中,一般会根据提供的类名列表来创建对象.
var vcArr: [UIViewController] = []
let nameArr = ["HomeController","MineController"]
for name in nameArr {if let tempVC = Tools.createObjWithClassName(name) as? UIViewController {vcArr.append(tempVC)}
}for vc in vcArr {if vc.className1 == "GAEmptyDataDemo.HomeController" {}if vc.className2 == "HomeController" {}
}
// MARK: 获取对象的类名
extension NSObject {var className1: String {return NSStringFromClass(type(of: self))}var className2: String {return String(describing: type(of: self))}static func className3(_ obj: Any) -> String {// prints more readable results for dictionaries, arrays, Int, etcreturn String(describing: type(of: obj))}}
import Foundationstruct Tools {// MARK: 使用类名实例化对象static func createObjWithClassName(_ className: String) -> NSObject {// 动态获取命名空间guard var spaceName = Bundle.main.infoDictionary!["CFBundleExecutable"] as? String else {print("获取命名空间失败")return NSObject()}spaceName = spaceName + "."// className:表示试图控制器的类名var vcClass: AnyClass?if className.contains(spaceName) {vcClass = NSClassFromString(className)} else {vcClass = NSClassFromString(spaceName + className)}// Swift中如果想通过一个Class来创建一个对象, 必须告诉系统这个Class的确切类型guard let typeClass = vcClass as? NSObject.Type else {print("vcClass不能当做UIViewController")return NSObject()}let createVC = typeClass.init()return createVC}}
这篇关于[Swift]获取对象的类名和使用类名创建对象的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!