简单实用的字典转模型的代码

在做字典转模型的时候,在写模型类属性的时候,是不是有好多属性来写,而且复制粘贴很麻烦,下面这段代码来解决你的麻烦。

第一步创建一个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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容