使用反射访问模型 class 的静态变量

Accessing static variables of a model class using reflection

我有一个模型 class,其中包含一些静态变量和属性。在运行时我可以获得属性;

let instance = entity.init()

let mirror = Mirror(reflecting:instance)

var propertyStrings = [String]()

for (propertyName, childMirror) in mirror.children {

}

但我也想获取 class 的静态变量作为列表。那么我怎样才能得到静态变量的名称和值的列表呢?这是我的模型 class' 结构:

class ActionModel: NSObject {

static let kLastModified = "LastModified"
static let kEntityName = "EntityName"
static let kIdentifier = "Id"


var lastModified: Int64
var entityName: String?
var identifier : PrimaryKeyString

尚不支持通过反射获取类型属性。如果将 class 对象传递给初始值设定项,您可以通过检查 MirrordisplayStyle 来看到这一点:

let mirror = Mirror(reflecting: ActionModel.self)
print(mirror.displayStyle)    // nil

您可以使用 Objective-c 运行时,尤其是描述 class 声明的属性的函数 class_copyPropertyList。示例:

import Foundation

class Foo:NSObject {
    @objc static var prop1: String? = "Hello I am prop1!"
    @objc static var prop2: String? = "Hello I am prop2!"
}

var count: CUnsignedInt = 0
let methods = class_copyPropertyList(object_getClass(Foo.self), &count)!
for i in 0 ..< count {
    let selector = property_getName(methods.advanced(by: Int(i)).pointee)
    if let key = String(cString: selector, encoding: .utf8) {
        let res = Foo.value(forKey: key)
        print("name: \(key), value: \(res ?? "")")
    }
}