美文网首页iOS开发iOS开发iOS学习
设计自己的模型属性代码

设计自己的模型属性代码

作者: ZhengYaWei | 来源:发表于2017-01-15 14:59 被阅读79次

将数据转为模型,是每一个app钟所必须的,通常对于复杂Device数据模型我们会采用第三方框架如JSONModel、YYModel等,但是针对一些比较简单的数据模型,就完全没有必要使用第三方框架。但是又不想自己手动敲打类似@property (nonatomic, strong) NSString *source; @property (nonatomic, assign) int reposts_count;等这样的代码,这是完全可以自己写一个分类,在这个分类中添加一个方法,直接传入一个字典,然后将类似在撒谎个面这样的代码自动打印在控制台。

在控制台打印自己的模型属性

直接创建一个NSObject的类别NSObject+Property,然后实现如下一个简单的方法即可。方法中的NSLog(@"%@",strM);会想相关信息打印在控制台。外部在调用这个方法的时候,直接传入数据中的任意一个相关字典就可以实现这个种效果,写好了这个类别,以后想使用的时候直接一行代码就可以实现打印自己的属性模型,省去了手动代码的麻烦,而且手动巧写代码的时候还有可能出错。还是很简单便捷的。😀😀😁😁

+ (void)createPropertyCodeWithDict:(NSDictionary *)dict{
    //@"@property(nonatomic,assign)int attitudes_count;";
    NSMutableString *strM = [NSMutableString string];
    //遍历字典
    [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull propertyName, id  _Nonnull value, BOOL * _Nonnull stop) {
        NSString *code;//属性代码
        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]
            ;
        }else if ([value isKindOfClass:NSClassFromString(@"__NSCFBoolean")]){
            code = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",propertyName]
            ;
        }
        [strM appendFormat:@"\n%@\n",code];
    }];
    
    NSLog(@"%@",strM);
}

相关文章

网友评论

    本文标题:设计自己的模型属性代码

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