Ios 我能';t使用swift by Class_copyPropertyList获取类的属性

Ios 我能';t使用swift by Class_copyPropertyList获取类的属性,ios,properties,swift,Ios,Properties,Swift,Model是我的自定义类,具有属性name(字符串)和age(int) 但是我什么也没有得到,您需要确保您的类子类来自NSObject,或者在类名前面添加@objc(我相信这在内部也是如此) class_copyPropertyList方法仅适用于NSObject子类,Swift类不是从中派生的。Swit 3版本 var infos = Model.getPropertiesInfo(); println("names = \(infos.propertiesName)");

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


但是我什么也没有得到,

您需要确保您的类子类来自NSObject,或者在类名前面添加@objc(我相信这在内部也是如此)


class_copyPropertyList方法仅适用于NSObject子类,Swift类不是从中派生的。

Swit 3版本

    var infos = Model.getPropertiesInfo();
    println("names = \(infos.propertiesName)");
    println("types = \(infos.propertiesType)");
扩展对象{ //转换成字典 func toDictionary(来自类类型:NSObject.Type)->[字符串:任意]{ var propertiesCount:CUnsignedInt=0 让PropertiesInClass=class\u copyPropertyList(类类型和属性计数) var propertiesDictionary=[String:Any]() 对于0中的i..它可以工作!我的错误!object\u getClass(AnyObject),这个母亲需要AnyObject,但是我给它传递了一个类名,所以它不工作!我相信“不,它不是。”class_copyPropertyList方法只适用于NSObject子类“不,Objectice-C运行时适用于所有Objective-C类。此外,您甚至可以将非Objective-C Swift类传递给Objective-C运行时函数,并且仍然可以获得一些信息。@newacct所有Objective-C类都派生自其类中的NSObjecthierarchy@SomeGuy:绝对不是。您可以随时通过不指定父类来定义根类。甚至Cocoa也附带了
NSProxy
Object
,这是不是从
NSObject
派生的其他根类。在类函数中,
self
是调用它的类
object\u getClass(self)
获取元类。这就是你想要的吗?
    var infos = Model.getPropertiesInfo();
    println("names = \(infos.propertiesName)");
    println("types = \(infos.propertiesType)");
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)