1.新建NSObject的分类(Model)
2.在NSObject+Model.h文件中声明一下函数:
+ (instancetype)modelWithDict:(NSDictionary *)dict;
3.在NSObject+Model.m文件中实现函数,代码如下:
#import "NSObject+Model.h"
#import <objc/message.h>
@implementation NSObject (Model)
+ (instancetype)modelWithDict:(NSDictionary *)dict
{
// 创建一个模型对象(由于不知道模型具体的类型,选择使用id)
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];
// 获取成员变量名称
NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];
// 获取成员变量类型
NSString *type = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
// 注:此时输出的type == @"@\"User\"";需转换为@"User"
// @"@\"User\"" -> @"User"
type = [type stringByReplacingOccurrencesOfString:@"@\"" withString:@""];
type = [type stringByReplacingOccurrencesOfString:@"\"" withString:@""];
// 成员变量名称转换key _user===>user
NSString *key = [ivarName substringFromIndex:1];
// 从字典中取出对应value dict[@"user"] -> 字典
id value = dict[key];
// 二级转换
// 当获取的value为字典时,且type是模型
// 即二级模型
if ([value isKindOfClass:[NSDictionary class]] && ![type containsString:@"NS"]) {
// 获取对应的类
Class className = NSClassFromString(type);
// 字典转模型
value = [className modelWithDict:value];
}
// 给模型中属性赋值
if (value) {
[objc setValue:value forKey:key];
}
}
return objc;
}
@end
4.使用在要使用的文件中导入NSObject+Model.h文件,创建一个测试的继承NSobject的TestModel类
下面是测试的代码:
TestModel.h
#import "NSObject+Model.h"
@interface TestModel : NSObject
@property (nonatomic,strong) NSString *avatarUrl;
@property (nonatomic,strong) NSString *nickname;
@property (nonatomic,strong) NSString *content;
@property (nonatomic,strong) NSString *type;
@property (nonatomic,strong) NSString *time;
@end
使用,代码如下:
-(void)test{
NSDictionary *dic=@{
@"avatarUrl":@"http://img.zcool.cn/community/017274582000cea84a0e282b576a32.jpg",
@"nickname":@"nickname",
@"content":@"input you nickname",
@"type":@"1",
@"time":@"2017-12-10"
};
TestModel *model =[TestModel modelWithDict:dic];
NSLog(@"%@",model.nickname);
}