我无法通过class_copyPropertyList使用swift获取类的属性

时间:2014-07-15 05:06:02

标签: ios properties swift

class func getPropertiesInfo() -> (propertiesName:[String], propertiesType:[String]) {
    var propertiesName:[String] = Array();
    var propertiesType:[String] = Array();

    var outCount:UInt32 = 0;
    var i:Int        = Int();

    var properties:UnsafePointer<objc_property_t> = class_copyPropertyList(object_getClass(self), &outCount);
    println("\(outCount)");
}

我用:

    var infos = Model.getPropertiesInfo();
    println("names = \(infos.propertiesName)");
    println("types = \(infos.propertiesType)");

Model是我的自定义类,具有属性name(字符串)和age(int)。

但我一无所获,

2 个答案:

答案 0 :(得分:5)

Swit 3版本

extension NSObject {

   // convert to dictionary
   func toDictionary(from classType: NSObject.Type) -> [String: Any] {

       var propertiesCount : CUnsignedInt = 0
       let propertiesInAClass = class_copyPropertyList(classType, &propertiesCount)
       var propertiesDictionary = [String:Any]()

       for i in 0 ..< Int(propertiesCount) {
          if let property = propertiesInAClass?[i],
             let strKey = NSString(utf8String: property_getName(property)) as String? {
               propertiesDictionary[strKey] = value(forKey: strKey)
          }
       }
       return propertiesDictionary
   }
}

// call this for NSObject subclass

let product = Product()
let dict = product.toDictionary(from: Product.self)
print(dict)

答案 1 :(得分:2)

你需要确保你的类是NSObject的子类,或者在你的类名前加上@objc(我认为内部也是这样)。

class_copyPropertyList方法只适用于NSObject子类,Swift类不能从中派生。