在做字典转模型的时候,在写模型类属性的时候,是不是有好多属性来写,而且复制粘贴很麻烦,下面这段代码来解决你的麻烦。
第一步创建一个NSDictionary的分类
第二步在.h文件中添加一个类方法
第三步在.m文件中实现这个类方法
#import "NSDictionary+PropertyCode.h"
// isKindOfClass:判断下是否是当前类或者子类
@implementation NSDictionary (PropertyCode)
// 自动生成,解析字典去生成,有多少key,就有多少个属性
- (void)propertyCode
{
NSMutableString *codes = [NSMutableString string];
// 遍历字典中所有key
[self enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull value, BOOL * _Nonnull stop) {
NSString *code;
if ([value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) {
code = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",key];
} else if ([value isKindOfClass:[NSString class]]) {
code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSString *%@;",key];
} else if ([value isKindOfClass:[NSArray class]]) {
code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSArray *%@;",key];
} else if ([value isKindOfClass:[NSDictionary class]]) {
code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSDictionary *%@;",key];
} else if ([value isKindOfClass:[NSNumber class]]) {
code = [NSString stringWithFormat:@"@property (nonatomic, assign) NSInteger %@;",key];
}
// 生成一行属性代码 reposts_count:@property (nonatomic, assign) NSInteger reposts_count;
[codes appendFormat:@"\n%@\n",code];
}];
NSLog(@"%@",codes);
}
@end