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

2019-01-22  本文已影响6人  张俊凯

@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
完。

上一篇下一篇

猜你喜欢

热点阅读