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

标签 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 {
    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.

constMethod1constMethod2是计算类属性,在 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/

相关文章:

swift - 如何禁用 NSView 上的鼠标单击和鼠标拖动?

swift5 - TableView Getter 的 Swift 5.3 编译器崩溃

iphone - 如何在 iphone 应用程序的搜索表中显示第一个词

ios - Swift:我怎样才能有一个监听器来报告连接何时丢失以及何时恢复?

swift - 多个 CoreData 实体的通用函数

ios - TableView 导航到 View Controller 和其他单元格中的其他操作

aes - Swift 5 + kCCDecrypt (CommonCrypto) : Failing to decrypt

ios - 如何设置动态宽度 UICollectionViewCell

ios - 如何设置可轻松跨越任何 iOS 设备的 UI?

ios - 在本地备份核心数据,并从备份中恢复 - Swift