自动生成属性的模型
利用 KVC 实现的自动生成属性的模型
掉用下面的方法
[NSObject createPropertyCodeWithNSDictionary:dataDic[0]];
在输出控制台输出属性模型, 利用kvc 属性名字与字典的 key 一一对应
但是 我们通常会遇到,字典 key为 id时,这个时候需要我们手动的去改一下属性的名字 ID
还有通常在遍历字典的时候,有的字典的属性有,有的字典没有这个属性,如果按照没有的字典生成的属性,那么有这个属性的字典,也需要我们手动去写上这个属性模型.
// // NSObject+Property.h // 字典转模型KVC实现 // // Created by Apple on 16/8/16. // Copyright © 2016年 叶炯. All rights reserved. // #import <Foundation/Foundation.h> @interface NSObject (Property) + (void)createPropertyCodeWithNSDictionary:(NSDictionary *)dict; @end
// // NSObject+Property.m // 字典转模型KVC实现 // // Created by Apple on 16/8/16. // Copyright © 2016年 叶炯. All rights reserved. // #import "NSObject+Property.h" @implementation NSObject (Property) + (void)createPropertyCodeWithNSDictionary:(NSDictionary *)dict { NSMutableString *str = [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) NSInteger %@;",propertyName]; }else if ([value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) {
code = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",propertyName];
}else if ([value isKindOfClass:NSClassFromString(@"__NSCFConstantString")]) {
code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSString *%@;",propertyName]; }else if ([value isKindOfClass:NSClassFromString(@"__NSCFDictionary")]) { code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSDictionary *%@;",propertyName]; }else if ([value isKindOfClass:NSClassFromString(@"__NSCFArray")]) { code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSArray *%@;",propertyName]; } [str appendFormat:@"\n%@\n",code]; }]; NSLog(@"*****%@*****",str); } @end