(小技巧)根据字典自动生成属性代码

日常开发中,我们拿到接口文档,会根据接口返回的数据来写模型。
在之前我都是根据返回的字典一个个key这样对照着来创建模型属性。后面遇到项目中有时候返回的数据里面要写成模型属性的key实在是太多,写起来花时间容易写错又没什么技术含量。
这时候就应该动用开发人员该有的程序思想了,干脆让它自动生成不就好了。废话不多说上代码。

- (void)createPropertyCode
{
    NSMutableString *codes = [NSMutableString string];
    // 遍历字典
    [self enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull value, BOOL * _Nonnull stop) {   
        NSString *code;
        if ([value isKindOfClass:[NSString class]]) {
            code = [NSString stringWithFormat:@"@property (nonatomic, strong) 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];
        }
        // @property (nonatomic, strong) NSString *source;     
        [codes appendFormat:@"\n%@\n",code];     
    }];
   NSLog(@"%@",codes);   
}

这个方法利用NSDictionary类里面的这个方法帮我们遍历字典里面所有的key和value,期间要做的事情写到block中,也就是帮我们自动生成属性代码。

- (void)enumerateKeysAndObjectsUsingBlock:(void (^ _Nonnull)(KeyType _Nonnull key, ObjectType _Nonnull obj, BOOL * _Nonnull stop))block

至于怎么用,可以写成NSDictionary的一个分类。然后用字典对象直接调用就好。像这样[dict createPropertyCode]。就可以帮我们打印出属性代码,然后复制粘贴就好。在面对属性超多的模型时,是不是方便许多了。
当然你也可以根据需要做一些调整,这里也只是提供一个开发中的小技巧,让机器帮我们做事往往

你可能感兴趣的:((小技巧)根据字典自动生成属性代码)