Swift 获取属性和方法列表

作者: WonderChang | 来源:发表于2016-07-14 16:22 被阅读644次

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

extension NSObject {
   
    func getPropertyNames(){
        
        var outCount:UInt32
        
        outCount = 0
        
        
        let propers:UnsafeMutablePointer<objc_property_t>! =  class_copyPropertyList(self.classForCoder, &outCount)
        
        
        let count:Int = Int(outCount);
        
        print(outCount)
        
        for i in 0...(count-1) {
            
            let aPro: objc_property_t = propers[i]
            
            let proName:String! = String(UTF8String: property_getName(aPro));
            
            print(proName)
            
        }
        
    }
    
    
    func getMethodNames(){
        
        var outCount:UInt32
        
        outCount = 0
        
        let methods:UnsafeMutablePointer<objc_property_t>! =  class_copyMethodList(self.classForCoder, &outCount)
        
        let count:Int = Int(outCount);
        
        print(outCount)
        
        for i in 0...(count-1) {
            
            let aMet: objc_property_t = methods[i]
            
            let methodName:String! = String(UTF8String: property_getName(aMet));
            
            print(methodName)
            
        }
        
    }
    
}

相关文章

网友评论

    本文标题:Swift 获取属性和方法列表

    本文链接:https://www.haomeiwen.com/subject/qgwejttx.html