运行时 获取属性列表


导入运行时头文件

#import <objc/runtime.h>

+ (NSArray *)getAttributesArrayWithModel:(NSObject *)model{

    
    // 属性字典
    NSMutableArray *attributes = [NSMutableArray array];
    
    // 获取当前类
    Class currentClass = [model class];
    
    // 获取当前类的属性描述集合
    unsigned int count;
    objc_property_t *properties = class_copyPropertyList(currentClass, &count);
    
    // 遍历集合
    for (unsigned int i=0; i<count; i++) {
        
        // 创建属性字典
        NSMutableDictionary *attribute = [NSMutableDictionary dictionary];
        
        // 获取属性的结构体指针
        objc_property_t property = properties[i];
        
        // 获取属性名称
        const char *cName = property_getName(property);
        
        // C字符转换成OC字符串
        NSString  *name = [NSString stringWithCString:cName encoding:NSUTF8StringEncoding];
        
        // 获取属性对应的值
        id value = [model valueForKey:name];
        
        if (name!=nil && value != nil) {
            
            // 编成字典添加到数据数组当中
            [attribute  setValue:value forKey:name];
            [attributes addObject:attribute];
        }
    }
    // 释放属性描述集合指针
    free(properties);
    
    return attributes;
}




//result.USA  // 数组

//KWPerson  类名

  [_result.USA enumerateObjectsUsingBlock:^(KWPerson *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            // 获取当前类的所有属性
            // 记录属性个数
            unsigned int count;
            objc_property_t *properties = class_copyPropertyList([obj class], &count);
            // 遍历
            NSMutableArray *mArray = [NSMutableArray array];
            for (int i = 0; i < count; i++) {
                
                objc_property_t property = properties[i];
                // 获取属性的名称 C语言字符串
                const char *cName = property_getName(property);
                NSString *name = [NSString stringWithCString:cName encoding:NSUTF8StringEncoding];
                id value = [obj valueForKey:name];
                
                if (name!=nil && value != nil) {
                    // 转换为Objective C 字符串
                    
                    [mArray addObject:name];
                }
            };
            self.count = mArray.count;
            MMLog(@"%lu",(unsigned long)mArray.count);
            
              free(properties);
        }];


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值