我有一个类使用可以从 objc-c 和 swift 访问的类计算变量。我想测试所有这些以“const”开头的属性。
我有这个:
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
}
}
我得到的只是返回数组中的“init”?问题是什么?我在另一个线程上看到,只需添加“@objc”即可解决此问题。另外,如何从重新调整的数组中访问这些变量之一?
最佳答案
来自 docs :
Describes the instance methods implemented by a class.
constMethod1
和 constMethod2
是计算类属性,在 Objective-C 中转换为类方法。所以它们不会被 class_copyMethodList
退回.但不要害怕,文档还说:To get the class methods of a class, use
class_copyMethodList(object_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)
}
关于ios - Swift 5 反射获取类属性列表并调用它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64010692/