美文网首页
关于iOS开发,一行代码搞定字典模型生成模型属性

关于iOS开发,一行代码搞定字典模型生成模型属性

作者: 丶逝水流年 | 来源:发表于2017-06-20 11:19 被阅读561次

    前言:一般情况下我们拿到数据都会有一个模型类,这时候要是属性少还好,要是属性多的话,那就苦逼了,能不能不用写这些垃圾代码?让系统自动生成数据模型里的所有属性呢?

    看一下这个plist文件里的结构,有不同的类型

    第一步:通过解析字典自动生成属性代码,新建一个NSObject的分类,写个类方法

    .h里的代码

    #import@interface NSObject (Property)

    +(void)createPropertyCodeWithDict:(NSDictionary *)dict;

    @end

    .m里的代码

    #import "NSObject+Property.h"

    @implementation NSObject (Property)

    +(void)createPropertyCodeWithDict:(NSDictionary *)dict{

    NSMutableString *strM = [NSMutableString string];

    //遍历字典

    [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull propertyName, id  _Nonnull value, BOOL * _Nonnull stop) {

    //属性代码

    NSString *code;

    //判断是什么类型,如果是这个类型就生成对应的代码,然后把打印出的代码复制到你的模型里就OK了

    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) int %@;",propertyName];

    }else if ([value isKindOfClass:NSClassFromString(@"__NSCFArray")]){

    code = [NSString stringWithFormat:@"@property (nonatomic,strong) NSArray *%@;",propertyName];

    }else if ([value isKindOfClass:NSClassFromString(@"__NSCFDictionary")]){

    code = [NSString stringWithFormat:@"@property (nonatomic,strong) NSDictionary *%@;",propertyName];

    }

    //打印数据换行

    [strM appendFormat:@"\n%@\n",code];

    }];

    //打印数据

    NSLog(@"strM == %@",strM);

    }

    @end

    第二步:调用这个分类的类方法

    #import "ViewController.h"

    #import "NSObject+Property.h"

    @interface ViewController ()

    @end

    @implementation ViewController

    - (void)viewDidLoad {

    [super viewDidLoad];

    NSString *filePath = [[NSBundle mainBundle]pathForResource:@"statuses.plist" ofType:nil];

    NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];

    NSArray *dictArray = dict[@"statuses"];

    [NSObject createPropertyCodeWithDict:dictArray[0]];

    }

    @end

    最后效果如下:

    只需要把打印出来的属性,直接复制到你的模型里就可以了,是不是很简单,很方便呢?觉得可以就收藏一波吧~~~

    相关文章

      网友评论

          本文标题:关于iOS开发,一行代码搞定字典模型生成模型属性

          本文链接:https://www.haomeiwen.com/subject/zkyoqxtx.html