iOS Swift 获取类名和动态创建加载类
2021-06-16 本文已影响0人
EitanLiu
获取类名
中文网络上搜出来的一堆都是错误的,第一种通过读取 CFBundleExecutable
作为命名空间的,那其它模块的同名怎么处理?第二种继承 NSObject
通过 description()
获取,那不继承的怎么获取?
class MyViewModel {}
// 获取带命名空间类名
print(String(reflecting: MyViewModel.self))
// 获取不带命名空间类名
print(String(describing: MyViewModel.self))
// 类实例获取类名
print(String(reflecting: type(of: MyViewModel())))
print(String(describing: type(of: MyViewModel())))
动态创建类
找到的基本都是 NSClassFromString
根据类名创建,同样的那不继承 NSObject
就不能创建了吗?
public protocol ViewModelType {
init()
}
public protocol ControllerViewModelType {
init(controller: UIViewController)
}
func create<T>(controller: UIViewController) -> T {
let type = T.self
if let type = type as? ControllerViewModelType.Type {
return type.init(controller: controller) as! T
} else if let type = type as? ViewModelType.Type {
return type.init() as! T
} else if let type = type as? NSObject.Type {
return type.init() as! T
} else {
fatalError("init() has not been implemented")
}
}
参考
keyword: swift dynamic create object
DynamicInit.swift