Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift 5反射获取类属性列表并调用它们_Ios_Swift_Swift5 - Fatal编程技术网

Ios Swift 5反射获取类属性列表并调用它们

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 {

我有一个类,它使用可以从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
    }
}
导入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)
}