如何将名称为 class 的字符串转换为 class 类型本身?

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

为了在日志文件中存储 class 名称,我将 class 类型的描述转换为字符串:

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

但是,我没有成功地将 str 反向转换为 NSObject.Type 类型的变量以在通用方法中使用它。

我该怎么做?

可能是这样的:

let objectType: NSObject.Type = NSObject.self 

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

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

我只是创建了一个可用于任何对象的扩展:

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)
    }

}

方法classForCoder用class名称打印出模块名称。然后您必须使用该字符串才能将其转换回其各自的对象类型。

您可以从 string 取回您的 class,但在获取 class 名称时需要使用项目的 模块 名称。如果您不使用您的模块名称,那么它将 return nil 因为您之前引用的 class 名称未完全符合 模块名称 .您应该更改 class 名称字符串以表示您的 class 的完全限定名称:

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