在开发过中每次字典转模型的时候都要写上一堆属性代码,那么有没有比较好的方法在解析的过程当中一次性生成属性代码,直接来cmd + c ,cmd + v 就搞定呢 ?
新建一个NSObject的分类:
NSObject+Property.h
#import <Foundation/Foundation.h>
@interface NSObject (Property)
+ (void)createPropertyCodeWithDict:(NSDictionary *)dict;
@end
NSObject+Property.m
#import "NSObject+Property.h"
@implementation NSObject (Property)
+ (void)createPropertyCodeWithDict:(NSDictionary *)dict
{
NSMutableString *strM = [NSMutableString string];
// 遍历字典
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull propertyName, id _Nonnull value, BOOL * _Nonnull stop) {
//NSLog(@"%@ %@",propertyName,[value class]);
NSString *code;
if ([value isKindOfClass:NSClassFromString(@"__NSCFString")]) {
code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSString *%@;",propertyName]
;
}else if ([value isKindOfClass:NSClassFromString(@"__NSCFNumber")]){
code = [NSString stringWithFormat:@"@property (nonatomic, assign) int %@;",propertyName]
;
}else if ([value isKindOfClass:NSClassFromString(@"__NSCFArray")]){
code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSArray *%@;",propertyName]
;
}else if ([value isKindOfClass:NSClassFromString(@"__NSCFDictionary")]){
code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSDictionary *%@;",propertyName]
;
}else if ([value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]){
code = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",propertyName]
;
}
[strM appendFormat:@"\n%@\n",code];
}];
NSLog(@"%@",strM);
}
@end
.m文件里面的类型不全,当遇到新的类型的时候可以再添加一个判断.
#import "ViewController.h"
#import "NSObject+Property.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"status.plist" ofType:nil];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
NSArray *dictArr = dict[@"statuses"];
// 设计模型属性代码
[NSObject createPropertyCodeWithDict:dictArr[0][@"user"]];
}
@end
然后按下cmd + R,控制台输出:

直接复制,粘贴到模型里面,是不是很爽啊.
网友评论