这儿主要会用到OC的NSClassFromString方法
extension String {
func stringTransformClass() -> AnyClass? {
guard let bundleName: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String else {
return nil
}
let classPath = bundleName + "." + self;
var anyClass: AnyClass? = NSClassFromString(classPath)
if (anyClass == nil) {
anyClass = NSClassFromString(self)
}
return anyClass
}
}
假如我定义了个如下类:
class Person:NSObject {
func study() {
print("开始学习")
}
}
guard let personClass = "Person".stringTransformClass() else {return}
guard let objectType = personClass as? NSObject.Type else {return}
guard let person = objectType.init() as? Person else {return}
person.study()
//打印开始学习