Swift 获取属性和方法列表

可利用反射机制获取某个类的属性及方法列表,代码很简单,重点用到class_copyPropertyList和class_copyMethodList,如下:

extension NSObject{

    /// 获取类的属性列表
    ///
    /// - Returns:  属性名列表
    func get_class_copyPropertyList()->[String]{
        var outCount:UInt32 = 0
        let propers:UnsafeMutablePointer! =  class_copyPropertyList(self.classForCoder, &outCount)
        let count:Int = Int(outCount);
        var names:[String] = [String]()
        for i in 0...(count-1) {
            let aPro: objc_property_t = propers[i]
            if let proName:String = String(utf8String: property_getName(aPro)){
                names.append(proName)
            }
        }
        return names
    }
    
    /// 获取类的方法列表
    ///
    /// - Returns: 方法名列表
    func get_class_copyMethodList() -> [String]{
        var outCount:UInt32
        outCount = 0
        let methods:UnsafeMutablePointer! =  class_copyMethodList(self.classForCoder, &outCount)
        let count:Int = Int(outCount);
        var names:[String] = [String]()
        for i in 0...(count-1) {
            
            let aMet: objc_property_t = methods[i]
            
            if let methodName:String = String(utf8String: property_getName(aMet)){
                names.append(methodName)
            }
        }
        return names
    }
}

你可能感兴趣的:(Swift 获取属性和方法列表)