I cannot get class properties using swift on 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 use:

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

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

But I get nothing

+8
source share
2 answers

You need to make sure that you subclass the classes from NSObject or add @objc in front of your class name (which internally does the same as I think).

The class_copyPropertyList method will work only in subclasses of NSObject, from which Swift classes are not derived.

+2
source

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) 
+4
source

Source: https://habr.com/ru/post/972221/


All Articles