美文网首页
字典转换模型时,自动生成模型的属性字符串

字典转换模型时,自动生成模型的属性字符串

作者: 张俊凯 | 来源:发表于2019-01-22 11:46 被阅读6次
    • 需求场景:
      需要新建一个模型,在模型里要挨个复制粘贴key,确定修饰类型
    • 解决思路:
      给字典建立一个分类,遍历字典,判断每一个值的类型,拼接上对应的修饰字符串,打印在控制台之后复制粘贴到模型的.h文件里,节约时间
    • 代码实现:
    
    @implementation NSDictionary (moreFunction)
    - (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, cppy) 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);
        
    }
    
    @end
    
    NSDictionary *dic = @{@"title":@"123123",
                              @"name":@"123123",
                              @"sex":@"123123"
                              };
        [dic autoCreatePropetyCode];
    
    • 控制台输出
    @property (nonatomic, cppy) NSString *title;
    
    @property (nonatomic, cppy) NSString *name;
    
    @property (nonatomic, cppy) NSString *sex;
    

    代码下载地址:https://github.com/zhangjk4859/iOSFactory
    完。

    相关文章

      网友评论

          本文标题:字典转换模型时,自动生成模型的属性字符串

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