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,
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With