我直接在昨晚的model类中进行代码操作了。mac下面没网络,只有手写,谅解哈
# .m文件中
+ (instancetype)modelWithDict:(NSDictionary *)dict{
// 创建对应类的对象
id objc =[[self alloc] init];
unsigned int count = 0;
Ivar *ivarList = class_copyIvarList(self, &count);
// 遍历
for (int i = 0; i< count; i++){
Ivar ivar = ivarList[i];
// 获取成员名(获取到的是C语言类型,需要转换为OC字符串)
NSString *propertyName = [NSString stringWithUTF8String:ivar_getName(ivar)];
// 成员属性类型
NSString *propertyType = [NSString stringWithUTF8String: ivar_getTypeEncoding(ivar)];
// 首先获取key(根据你的propertyName 截取字符串)
NSString *key = [propertyName substringFromIndex:1];
// 获取字典的value
id value = dict[key];
/**
这里根据值进行判断后面的元素是否存在字典
二级转换:值是字典,成员属性不是字典才需要转换为模型
*/
if([value isKindOfClass:[NSDictonary Class]] && [propertyType containsString:@"NS"]){ // 需要字典转换成模型
// 转换成哪个类型
// 获取的propertyType 样式:@"@\"User\""
// 字符串的截取
NSRange range = [properType rangeOfString:@"\"]; // 第一个 \
propertyType = [propertyType substringFromIndex:range.location + range.length];
range = [properType rangeOfString:@"\"]; // 第二个 \
propertyType = [propertyType substringToIndex:range.location];
// 获取需要转换类的类对象
Class modelClass = NSClassFromString(propertyType);
if(modelClass){
value = [modelClass modelWithDict:value]; // 调用字典转模型的方法
{
{
// 给模型的属性赋值
// value : 字典的值
// key : 属性名
if (value){ // 这里是因为KVC赋值,不能为空
[objc setValue:value forKey:key];
}
NSLog(@"%@ %@",propertyType,propertyName);
}
NSLog(@"%zd",count); // 这里会输出self中成员属性的总数
return objc;
}