导入运行时头文件
#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);
}];