runtime获取类属性列表和方法列表

获取对象的所有属性

/* 获取对象的所有属性 */
+(NSArray *)getAllProperties
{
    u_int count;
    // 传递count的地址过去 &count
    objc_property_t *properties  =class_copyPropertyList([self class], &count);
    //arrayWithCapacity的效率稍微高那么一丢丢
    NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];

    for (int i = 0; i < count ; i++)
    {
        //此刻得到的propertyName为c语言的字符串
        const char* propertyName =property_getName(properties[i]);
        //此步骤把c语言的字符串转换为OC的NSString
        [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
    }
    //class_copyPropertyList底层为C语言,所以我们一定要记得释放properties
    // You must free the array with free().
    free(properties);

    return propertiesArray;
}  ```
#### 获取对象所有方法

/* 获取对象的所有方法 */
+(NSArray )getAllMethods
{
unsigned int methodCount =0;
Method
methodList = class_copyMethodList([self class],&methodCount);
NSMutableArray *methodsArray = [NSMutableArray arrayWithCapacity:methodCount];

for(int i=0;i<methodCount;i++)
{
    Method temp = methodList[i];
    IMP imp = method_getImplementation(temp);
    SEL name_f = method_getName(temp);
    const char* name_s =sel_getName(method_getName(temp));
    int arguments = method_getNumberOfArguments(temp);
    const char* encoding =method_getTypeEncoding(temp);
    NSLog(@"方法名:%@,参数个数:%d,编码方式:%@",[NSString stringWithUTF8String:name_s],
          arguments,
          [NSString stringWithUTF8String:encoding]);
    [methodsArray addObject:[NSString stringWithUTF8String:name_s]];
}
free(methodList);
return methodsArray;

} ```

获取对象的所有属性和属性内容

/* 获取对象的所有属性和属性内容 */
+ (NSDictionary *)getAllPropertiesAndVaules:(NSObject *)obj
{
    NSMutableDictionary *propsDic = [NSMutableDictionary dictionary];
    unsigned int outCount;
    objc_property_t *properties =class_copyPropertyList([obj class], &outCount);
    for ( int i = 0; i<outCount; i++)
    {
        objc_property_t property = properties[i];
        const char* char_f =property_getName(property);
        NSString *propertyName = [NSString stringWithUTF8String:char_f];
        id propertyValue = [obj valueForKey:(NSString *)propertyName];
        if (propertyValue) {
            [propsDic setObject:propertyValue forKey:propertyName];
        }
    }
    free(properties);
    return propsDic;
} ```

#### 用的时候记得导入头文件

import <objc/runtime.h> ```

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,837评论 18 139
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,082评论 6 13
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,841评论 25 708
  • 1.对于推送证书,只要生成新的推送证书,并将p.12文件传至相应推送开放平台即可。2.对于发布证书,过期不会影响线...
    ONE2阅读 6,207评论 0 1
  • 读完 刘飞的《从点子到产品》,写得比较实在,简要记录几下几点。 1、好产品的留存率 Facebook 曾经提出过一...
    GaryZhang阅读 681评论 0 51