一. 缘由
由于经常使用字典转模型,但是模型的属性的对照plist文件一个个添加,太过于浪费时间, 故创建一个字典分类使其自自动输出属性;
二.实现
给系统的字典类添加分类
在分类实现方法
#import "NSDictionary+PropertyCode.h"
@implementation NSDictionary (PropertyCode)
- (void)autoCreatePropetyCode
{
// 模型中属性一一对应字典的key
// 有多少个key,则生成多少个属性
// 创建可变字符串用于拼接属性
NSMutableString *codes = [NSMutableString string];
// 遍历字典
[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);
}
// 解析:
1.0 对于BOOL类型的属性,由于其是NSNumber的子类故需要放到NSNumber的前面先进行判断;
2.0 且打印出BOOL的类型是"__NSCFBoolean", 是苹果一个私有的API;
3.0 可利用:NSClassFromString(@"__NSCFBoolean")获取BOOL的类对象;
@end
三.验证
// 解析Plist
// 获取文件全路径
NSString *fileName = [[NSBundle mainBundle] pathForResource:@"status.plist" ofType:nil];
// 获取字典
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:fileName];
// 自动生成属性代码
[dict autoCreatePropetyCode];
最后把打印的属性代码copy到模型即可.