- 拿到属性之后,用KVC的方法进行赋值,这是所有第三方字典转模型的核心算法!
#import "NSObject+KAKARunTime.h"#import@implementation NSObject (KAKARunTime)
+ (instancetype) KAKA_objWithDictionary:(NSDictionary* ) dictionary{
id object = [[self alloc] init];
//获取对象的属性
NSArray* propertyList = [self KAKA_ObjProperties];
//遍历字典进行判断
[dictionary enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
//判断当下的Key是否是在数组当中
if ([propertyList containsObject:key]) {
//如果包含KVC赋值
[object setValue:obj forKey:key];
}
}];
return object;
}
/**
获取属性数组
@return 属性数组
*/
+ (NSArray *) KAKA_ObjProperties{
NSMutableArray * pArray = [[NSMutableArray alloc]init];
unsigned int count = 0 ;
objc_property_t * propertylist = class_copyPropertyList([self class], &count);
NSLog(@"%zd",count);
for (int i = 0; i < count ; i++) {
objc_property_t pty = propertylist[i];
const char * cName = property_getName(pty);
NSString * pString = [NSString stringWithCString:cName encoding:NSUTF8StringEncoding];
[pArray addObject:pString];
}
free(propertylist);
return pArray.copy;
}
@end