在网络请求或加载plist文件时,常会获得一个字典。我们通常会将字典转为模型。就避免不了在类的.h文件声明属性,这是一个重复的工作,我们如何偷懒呢?
假设我们拥有一个plist文件,我们需要对其模型化。首先我们加载这个文件
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 获取文件全路径
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"status.plist" ofType:nil];
// 文件全路径
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];
// 设计模型,创建属性代码 => dict
[dict createPropertyCode];
}
其次我们声明一个NSDictionary
的分类,实现方法createPropertyCode
@interface NSDictionary (Property)
- (void)createPropertyCode;
@end
@implementation NSDictionary (Property)
// isKindOfClass:判断是否是当前类或者子类
// 生成属性代码 => 根据字典中所有key
- (void)createPropertyCode
{
NSMutableString *codes = [NSMutableString string];
// 遍历字典
[self enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull value, BOOL * _Nonnull stop) {
NSString *code;
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];
}
// @property (nonatomic, strong) NSString *source;
[codes appendFormat:@"\n%@\n",code];
}];
NSLog(@"%@",codes);
}
@end
当viewDidLoad
执行到[dict createPropertyCode];
时,就会打印出所有的属性列表:
2016-09-12 11:23:18.646 05-Runtime(****字典转模型****KVC****实现****)[11614:103900] **
@property (nonatomic, strong) NSString *source;
@property (nonatomic, assign) NSInteger reposts_count;
@property (nonatomic, strong) NSArray *pic_urls;
@property (nonatomic, strong) NSString *created_at;
@property (nonatomic, assign) BOOL isA;
@property (nonatomic, assign) NSInteger attitudes_count;
@property (nonatomic, strong) NSString *idstr;
@property (nonatomic, strong) NSString *text;
@property (nonatomic, assign) NSInteger comments_count;
@property (nonatomic, strong) NSDictionary *user;
这是在看小马哥视频时,学习到的方法,记录下来。