字典轉(zhuǎn)模型的時候,雖然可以使用第三方框架MJExtension等轉(zhuǎn)換,但是模型的屬性還是要自己對著開發(fā)文檔或者返回的數(shù)據(jù)打印出來去敲,這部分代碼,來回切換,復(fù)制粘貼,沒有技術(shù)含量,但是如果屬性多的話,還是有可能有些差錯,盡管很容易找出來,但是這種代碼還是能偷懶最好啦
下面我介紹一個簡單的生成模型屬性的方法,就是給NSDictionary添加分類,寫一個方法就好,代碼如下:
#import "NSDictionary+PropertyCode.h"
@implementation NSDictionary (PropertyCode)
-(void) creatPropertyCode{
NSMutableString *codes = [NSMutableString string];
// 遍歷字典,根據(jù)key生成屬性
[self enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull value, BOOL * _Nonnull stop) {
NSString *code = nil;
if ([value isKindOfClass:[NSString class]]) {
code = [NSString stringWithFormat:@"@property (nonatomic,strong) NSString *%@;",key];
}else if ([value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) {
code = [NSString stringWithFormat:@"@property (nonatomic,assign) BOOL %@;",key];
}else if ([value isKindOfClass:[NSNumber class]]) {
code = [NSString stringWithFormat:@"@property (nonatomic,assign) NSInteger %@;",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];
}
[codes appendFormat:@"\n%@\n",code];
}];
NSLog(@"%@",codes);
}
@end
在分類添加這個方法后就可以讓需要轉(zhuǎn)為模型的字典調(diào)用該方法,打印出你需要的屬性代碼了,然后適當修改就好了~