1.新建NSObject的分類(Model)
2.在NSObject+Model.h文件中聲明一下函數(shù):
+ (instancetype)modelWithDict:(NSDictionary *)dict;
3.在NSObject+Model.m文件中實現(xiàn)函數(shù)庆捺,代碼如下:
#import "NSObject+Model.h"
#import <objc/message.h>
@implementation NSObject (Model)
+ (instancetype)modelWithDict:(NSDictionary *)dict
{
// 創(chuàng)建一個模型對象(由于不知道模型具體的類型,選擇使用id)
id objc = [[self alloc] init];
unsigned int count = 0;
// 獲取成員變量數(shù)組
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\"";需轉(zhuǎn)換為@"User"
// @"@\"User\"" -> @"User"
type = [type stringByReplacingOccurrencesOfString:@"@\"" withString:@""];
type = [type stringByReplacingOccurrencesOfString:@"\"" withString:@""];
// 成員變量名稱轉(zhuǎn)換key _user===>user
NSString *key = [ivarName substringFromIndex:1];
// 從字典中取出對應value dict[@"user"] -> 字典
id value = dict[key];
// 二級轉(zhuǎn)換
// 當獲取的value為字典時,且type是模型
// 即二級模型
if ([value isKindOfClass:[NSDictionary class]] && ![type containsString:@"NS"]) {
// 獲取對應的類
Class className = NSClassFromString(type);
// 字典轉(zhuǎn)模型
value = [className modelWithDict:value];
}
// 給模型中屬性賦值
if (value) {
[objc setValue:value forKey:key];
}
}
return objc;
}
@end
4.使用在要使用的文件中導入NSObject+Model.h文件滔以,創(chuàng)建一個測試的繼承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);
}