Ios Swift 5反射获取类属性列表并调用它们
我有一个类,它使用可以从objc-c和swift访问的类计算变量。我想测试所有这些以“const”开头的属性 我有这个:Ios Swift 5反射获取类属性列表并调用它们,ios,swift,swift5,Ios,Swift,Swift5,我有一个类,它使用可以从objc-c和swift访问的类计算变量。我想测试所有这些以“const”开头的属性 我有这个: import UIKit class MyClass: NSObject { @objc class var constMethod1 : UIColor { print("Method1") return UIColor.red } @objc class var constMethod2 : UIColor {
import UIKit
class MyClass: NSObject {
@objc class var constMethod1 : UIColor {
print("Method1")
return UIColor.red
}
@objc class var constMethod2 : UIColor {
print("Method2")
return UIColor.green
}
}
var methodCount: UInt32 = 0
let methodList = class_copyMethodList(MyClass.self, &methodCount)
for i in 0..<Int(methodCount){
let unwrapped = methodList?[i]
// call method only if it starts with "const"
let crtMethodStr = NSStringFromSelector(method_getName(unwrapped!))
print(crtMethodStr)
if crtMethodStr.hasPrefix("const") {
// call it
}
}
导入UIKit
类MyClass:NSObject{
@objc类变量constMethod1:UIColor{
打印(“方法1”)
返回UIColor.red
}
@objc类变量constMethod2:UIColor{
打印(“方法2”)
返回UIColor.green
}
}
var methodCount:UInt32=0
let methodList=class\u copyMethodList(MyClass.self和methodCount)
对于0..中的i,从:
描述由类实现的实例方法
constMethod1
和constMethod2
是计算类属性,在Objective-C中转换为类方法。因此,class\u copyMethodList
不会返回它们。但别担心,这些文件还说:
要获取类的类方法,请使用class\u copyMethodList(object\u getClass(cls),&count)
因此,您可以:
let methodList = class_copyMethodList(object_getClass(MyClass.self), &methodCount)
要调用它,可以使用perform
:
if crtMethodStr.hasPrefix("const") {
let result = MyClass.perform(method_getName(unwrapped!))!.takeUnretainedValue()
print(result)
}