Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't get properties of a Class using swift by class_copyPropertyList

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)");
}

I using:

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

Model is my custom Class, has properties name(String) and age(int).

But i get nothing,

like image 930
user3839355 Avatar asked Jul 15 '14 05:07

user3839355


1 Answers

Swit 3 Version

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)
like image 166
rushisangani Avatar answered Oct 31 '22 12:10

rushisangani