一.自动生成属性的分类
模型属性,通常需要跟字典中的key一一对应。从服务器得到的数据太杂?数据太多?写成plist文件后一个个对照填写属性,太繁琐?那么我么可以尝试写一个分类来自动打印出所有属性。
• 需求:能不能根据一个字典,自动生成对应的属性。
• 解决:提供一个分类,专门根据字典生成对应的属性字符串。
images/loading.gif' data-original="http://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif" />
1 #import <Foundation/Foundation.h> 2 3 @interface NSDictionary (PropertyCode) 4 5 // 生成属性代码 6 - (void)createPropetyCode; 7 @end 8 9 @implementation NSDictionary (PropertyCode)10 // 私有API:真实存在,但是苹果没有暴露出来,不给你用11 // isKindOfClass:判断下是否是当前类或者子类12 // 自动生成属性代码13 - (void)createPropetyCode14 {15 NSMutableString *codes = [NSMutableString string];16 // 遍历字典17 [self enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull value, BOOL * _Nonnull stop) {18 NSString *code = nil;19 20 if ([value isKindOfClass:[NSString class]]) {// 注:NSString *笔者喜欢用strong,若想使用copy可修改字符串21 code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSString *%@;",key];22 } else if ([value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]){23 code = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",key];24 } else if ([value isKindOfClass:[NSNumber class]]) {25 code = [NSString stringWithFormat:@"@property (nonatomic, assign) NSInteger %@;",key];26 } else if ([value isKindOfClass:[NSArray class]]) {27 code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSArray *%@;",key];28 } else if ([value isKindOfClass:[NSDictionary class]]) {29 code = [NSString stringWithFormat:@"@property (nonatomic, strong) NSDictionary *%@;",key];30 }31 32 // 拼接字符串33 [codes appendFormat:@"\n%@\n",code];34 35 }];36 37 NSLog(@"%@",codes);38 }39 @end
分类NSDictionary+PropertyCode
外界使用:
1 #import "ViewController.h" 2 #import "Status.h" 3 #import "NSDictionary+PropertyCode.h" 4 /* 5 plist: 6 字典 7 字典转模型 8 */ 9 10 @interface ViewController ()11 12 @end13 14 @implementation ViewController15 16 - (void)viewDidLoad {17 [super viewDidLoad];18 19 // 解析Plist20 // 获取文件全路径21 NSString *fileName = [[NSBundle mainBundle] pathForResource:@"status.plist" ofType:nil];22 // 获取字典23 NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:fileName];24 25 // 设计模型-定义属性26 // 自动生成属性代码27 [dict createPropetyCode];28 }29 @end
ViewController
status.plist
2016-04-15 10:43:34.959 Runtime(自动生成属性)[38837:1398902]@property (nonatomic, assign) BOOL aaa;@property (nonatomic, assign) NSInteger reposts_count;@property (nonatomic, copy) NSString *source;@property (nonatomic, strong) NSArray *pic_urls;@property (nonatomic, copy) NSString *created_at;@property (nonatomic, assign) NSInteger attitudes_count;@property (nonatomic, copy) NSString *idstr;@property (nonatomic, copy) NSString *text;@property (nonatomic, assign) NSInteger comments_count;@property (nonatomic, strong) NSDictionary *user;
控制台打印信息
二.字典转模型KVC实现
KVC必须要保证:模型中属性名要跟字典中key一一对应。
需求:开发中,通常后台会给你很多数据,但是并不是每个数据都有用,这些没有用的数据,需不需要保存到模型中?
原标题:教你使用runtime写一个简单的字典转模型的工具类
关键词: