runtime 获取属性 和 成员变量不清楚的先看
- 给 NSObject 添加分类
NSObject+DicToModel.h
#import <Foundation/Foundation.h>
@interface NSObject (DicToModel)
+ (instancetype)modelWithDic:(NSDictionary *)dic;
@end
NSObject+DicToModel.m
#import <objc/runtime.h>
#import "NSObject+DicToModel.h"
@implementation NSObject (DicToModel)
// 字典转模型
+ (instancetype)modelWithDic:(NSDictionary *)dic {
id obj = [[self alloc] init];
Class tClass = [self class];
unsigned int count = 0;
Ivar *ivalList = class_copyIvarList(tClass, &count);
for (int i = 0; i < count; i++) {
Ivar ivar = ivalList[i];
// 成员变量名称
const char *charName = ivar_getName(ivar);
NSString *name = [NSString stringWithUTF8String:charName];
// 成员变量类型
const char *charType = ivar_getTypeEncoding(ivar);
NSString *type = [NSString stringWithUTF8String:charType];
// 将 name 和 type 整理
name = [name substringFromIndex:1];
type = [type substringFromIndex:2];
type = [type substringToIndex:[type length] - 1];
// 根据name (也就是与字典的key对应)取出 value
NSString *key = [name copy];
id value = dic[name];
// 二级转换
if ([value isKindOfClass:[NSDictionary class]]) {
Class nClass = NSClassFromString(type);
value = [nClass modelWithDic:value];
}
// 三级转换
if ([value isKindOfClass:[NSArray class]]) {
NSMutableArray *mutArray = [NSMutableArray array];
NSArray *array = (NSArray *)value;
for (NSInteger i = 0; i < [array count]; i++) {
NSDictionary *mapping = [self performSelector:@selector(getMapping)];
Class interClass = mapping[key];
id interObj = [interClass modelWithDic:array[i]];
[mutArray addObject:interObj];
}
value = [mutArray copy];
}
[obj setValue:value forKey:key];
}
free(ivalList);
return obj;
}
- 新建立 Model 文件
TYLModel.h
#import <Foundation/Foundation.h>
#import "User.h"
@interface TYLModel : NSObject
@property (nonatomic, copy) NSString *content;
@property (nonatomic, strong) User *user;
@property (nonatomic, strong) NSArray<User *> *userArray;
@end
TYLModel.m
#import "TYLModel.h"
#import "User.h"
@implementation TYLModel
+ (NSDictionary *)getMapping {
return [NSDictionary dictionaryWithObjectsAndKeys:[User class], @"userArray", nil];
}
@end
User.h
#import <Foundation/Foundation.h>
@interface User : NSObject
@property (nonatomic, copy) NSString *account;
@end
User.m
#import "User.h"
@implementation User
@end
开始测试
记得导入头文件#import "NSObject+DicToModel.h"
NSDictionary *dic = @{@"content" : @"hello tyler",
@"user" : @{@"account" :@12342},
@"userArray": @[@{@"account" : @8888}]};
TYLModel *model = [TYLModel modelWithDic:dic];
User *user = model.userArray[0];
NSLog(@"%@",user.account);
网友评论