How to convert a string with the name of a class to the class type itself?

╄→гoц情女王★ 提交于 2019-12-06 23:17:19

问题


In order to store a class name in a log file I converted the description of a class type to a string:

let objectType: NSObject.Type = Object.self
let str = String(describing: objectType)

However, I do not succeed in back conversion of str to a variable of type NSObject.Type to use it in a generic method.

How could I do this?


回答1:


You can get your class back from string, but you need to use your project's module name while getting class name. If you don't use your module name then it will return nil because the class name you have referenced earlier is not fully qualified by the module name. You should change the class name string to represent the fully qualified name of your class:

let myClassString = String(MyModule.MyViewController.self)
print(myClassString)
let myClass = NSClassFromString("MyModule.\(myClassString)") as! MyViewController.Type
print(myClass)



回答2:


I simply created an extension to use on any object:

extension NSObject {

    // Save Name of Object with this method
    func className() -> String {

        return NSStringFromClass(self.classForCoder)

    }

    // Convert String to object Type
    class func objectFromString(string: String) -> AnyObject? {
        return NSClassFromString(string)
    }

}

The method classForCoder prints out the module name with the class name. Then you must that string in order to convert it back to its respective object type.




回答3:


Perhaps something like:

let objectType: NSObject.Type = NSObject.self 

let str = String(objectType) // str = "NSObject"

let aClass = NSClassFromString(str) as! NSObject.Type // aClass = NSObject.Type


来源:https://stackoverflow.com/questions/39668370/how-to-convert-a-string-with-the-name-of-a-class-to-the-class-type-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!