- 拿到屬性之后,用KVC的方法進(jìn)行賦值,這是所有第三方字典轉(zhuǎn)模型的核心算法!
#import "NSObject+KAKARunTime.h"#import@implementation NSObject (KAKARunTime)
+ (instancetype) KAKA_objWithDictionary:(NSDictionary* ) dictionary{
id object = [[self alloc] init];
//獲取對(duì)象的屬性
NSArray* propertyList = [self KAKA_ObjProperties];
//遍歷字典進(jìn)行判斷
[dictionary enumerateKeysAndObjectsUsingBlock:^(id? _Nonnull key, id? _Nonnull obj, BOOL * _Nonnull stop) {
//判斷當(dāng)下的Key是否是在數(shù)組當(dāng)中
if ([propertyList containsObject:key]) {
//如果包含KVC賦值
[object setValue:obj forKey:key];
}
}];
return object;
}
/**
獲取屬性數(shù)組
@return 屬性數(shù)組
*/
+ (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