【问题标题】:Swift 5 reflection get list of class properties and call themSwift 5反射获取类属性列表并调用它们
【发布时间】:2021-01-08 15:15:37
【问题描述】:

我有一个类使用可以从 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”就可以解决这个问题。另外,如何从重新调整的数组中访问这些变量之一?

【问题讨论】:

    标签: ios swift swift5


    【解决方案1】:

    来自docs

    描述类实现的实例方法。

    constMethod1constMethod2 是计算出来的 class 属性,它转换为 Objective-C 中的 class 方法。所以class_copyMethodList 不会返回它们。但不要害怕,文档还说:

    要获取某个类的类方法,请使用class_copyMethodList(object_getClass(cls), &amp;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)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-29
      • 2018-06-05
      • 2012-01-21
      • 2017-06-10
      相关资源
      最近更新 更多