1、一句代码自动生成模型属性
.h文件
#import <Foundation/Foundation.h>
@interface NSDictionary (Property)
- (void)createPropertyCode;
@end
.m文件
#import "NSDictionary+Property.h"
@implementation NSDictionary (Property)
- (void)createPropertyCode{
[self enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSString *code = nil;
if ([obj isKindOfClass:[NSString class]]) {
code = [NSString stringWithFormat:@"@property (nonatomic, copy) NSString *%@;",key];
}else if ([obj isKindOfClass:[NSNumber class]]){
code = [NSString stringWithFormat:@"@property (nonatomic, assign) NSInteger %@;",key];
}else if ([obj isKindOfClass: NSClassFromString(@"__NSCFBoolean")]){
code = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",key];
}else if ([obj isKindOfClass:[NSArray class]]) {
code = [NSString stringWithFormat:@"@property (nonatomic, copy) NSArray *%@;",key];
} else if ([obj isKindOfClass:[NSDictionary class]]) {
code = [NSString stringWithFormat:@"@property (nonatomic, copy) NSDictionary *%@;",key];
}
[codes appendFormat:@"\n%@\n",code];
}];
NSLog(@"%@",codes);
}
@end
2、字典转模型
.h文件
#import <Foundation/Foundation.h>
@interface XSDictModel : NSObject
//字典转模型
+ (instancetype)modelWithDict:(NSDictionary *)dict;
@end
.m文件
#import "XSDictModel.h"
#import <objc/message.h>
@implementation XSDictModel
+ (instancetype)modelWithDict:(NSDictionary *)dict{
id objc = [[self alloc] init];
//1.获取成员变量
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 *ivarType = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
ivarType = [ivarType stringByReplacingOccurrencesOfString:@"\"" withString:@""];
ivarType = [ivarType stringByReplacingOccurrencesOfString:@"@" withString:@""];
//获取key
NSString *key = [ivarName substringFromIndex:1];
id value = dict[key];
// 二级转换:判断下value是否是字典,如果是,字典转换层对应的模型
// 并且是自定义对象才需要转换
if ([value isKindOfClass:[NSDictionary class]] && ![ivarType hasPrefix:@"NS"]){
//获取class
Class modelClass = NSClassFromString(ivarType);
value = [modelClass modelWithDict:value];
}
if (value) {
[objc setValue:value forKey:key];
}
}
return objc;
}