在项目中经常会遇到将网络请求下的JSON字典转化成自定义模型的情况,通常模型的属性名跟字典中的Key值一一对应,如果仅仅通过复制粘贴的方法效率会很差,所以可以根据如下介绍的自动生成属性的代码提高工作效率
设计模型:字典转模型的第一步
模型属性,通常需要跟字典中的key一一对应
问题:一个一个的生成模型属性,很慢?
需求:能不能自动根据一个字典,生成对应的属性。
解决:提供一个分类,专门根据字典生成对应的属性字符串。
新建NSObject 的分类
.h
//
// NSObject+AutoProperty.h
// RuntimeDemo
//
// Created by 邱学伟 on 16/9/8.
// Copyright © 2016年 邱学伟. All rights reserved.
// 自动生成属性列表
#import <Foundation/Foundation.h>
@interface NSObject (AutoProperty)
/**
* 自动生成属性列表
*
* @param dict JSON字典/模型字典
*/
+(void)printPropertyWithDict:(NSDictionary *)dict;
@end
.m
//
// NSObject+AutoProperty.m
// RuntimeDemo
//
// Created by 邱学伟 on 16/9/8.
// Copyright © 2016年 邱学伟. All rights reserved.
//
#import "NSObject+AutoProperty.h"
@implementation NSObject (AutoProperty)
/**
* 自动生成属性列表
*
* @param dict JSON字典/模型字典
*/
+(void)printPropertyWithDict:(NSDictionary *)dict{
NSMutableString *allPropertyCode = [[NSMutableString alloc]init];
[dict enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSString *oneProperty = [[NSString alloc]init];
if ([obj isKindOfClass:NSClassFromString(@"__NSCFString")]) {
oneProperty = [NSString stringWithFormat:@"@property (nonatomic, copy) NSString *%@;",key];
}else if ([obj isKindOfClass:NSClassFromString(@"__NSCFNumber")]){
oneProperty = [NSString stringWithFormat:@"@property (nonatomic, assign) NSInteger %@;",key];
}else if ([obj isKindOfClass:NSClassFromString(@"__NSCFArray")]){
oneProperty = [NSString stringWithFormat:@"@property (nonatomic, strong) NSArray *%@;",key];
}else if ([obj isKindOfClass:NSClassFromString(@"__NSCFDictionary")]){
oneProperty = [NSString stringWithFormat:@"@property (nonatomic, strong) NSDictionary *%@;",key];
}else if ([obj isKindOfClass:NSClassFromString(@"__NSCFBoolean")]){
oneProperty = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;)",key];
}
[allPropertyCode appendFormat:@"\n%@\n",oneProperty];
}];
NSLog(@"%@",allPropertyCode);
}
@end
使用:
/**
* 自动生成模型属性列表
* 在解析JSON字典或本地字典处,利用自定义分类中的 printPropertyWithDict 类方法直接可以将字典中所有key转化为自定义模型中的属性名
*/
-(void)autoProperty{
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"status.plist" ofType:nil]];
NSArray *dictArr = dict[@"statuses"];
// 设计模型属性代码
[NSObject printPropertyWithDict:dictArr[0][@"user"]];
}
即将解析的字典
解析完成后的属性字符
然后可将打印的属性值直接拷贝到自己自定义模型中的.h声明文件中
此分类Demo下载地址:https://github.com/qxuewei/XWNSObject-AutoProperty