我有一个类,它使用类计算变量,这些变量可以从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“应该修复这个问题。另外,如何从重新调整的数组中访问这些变量之一?
发布于 2020-09-22 13:35:44
来自文档
描述由类实现的实例方法。
constMethod1和constMethod2是计算类的性质,它转化为目标C中的类方法。所以他们不会被class_copyMethodList归还。但不要害怕,医生们也说:
要获得类的类方法,请使用
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)
}https://stackoverflow.com/questions/64010692
复制相似问题