iOS 自动生成数据model

在定义model的时候,经常会写一大堆的属性声明和属性赋值,为了避免重复劳动,我们可以写个小程序拼接出属性声明的代码,赋值可以利用kvc setValuesForKeysWithDictionary的方法

  • 自动生成属性

生成属性代码可以在项目中写个分类 NSObject+AutoProperty

.h

//
//  NSObject+AutoProperty.h
//  GCDDemo
//
//  Created by z on 2017/1/19.
//  Copyright © 2017年 ja. All rights reserved.
// 传入数据字典自动生成属性代码

#import <Foundation/Foundation.h>

@interface NSObject (AutoProperty)
+ (void)autoPropertyWith:(NSDictionary *)dic;

@end

.m

#import "NSObject+AutoProperty.h"

@implementation NSObject (AutoProperty)
+ (void)autoPropertyWith:(NSDictionary *)dic
{
     NSMutableString *proprety = [[NSMutableString alloc] init];
    //遍历数组 生成声明属性的代码,例如 @property (nonatomic, copy) NSString str
    //打印出来后 command+c command+v
    [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        NSString *str;
        
        NSLog(@"%@",[obj class]);
        if ([obj isKindOfClass:NSClassFromString(@"__NSCFString")] || [obj isKindOfClass:NSClassFromString(@"NSTaggedPointerString")] || [obj isKindOfClass:NSClassFromString(@"__NSCFConstantString")]) {
            str = [NSString stringWithFormat:@"@property (nonatomic, strong) NSString *%@;",key];
        }
        if ([obj isKindOfClass:NSClassFromString(@"__NSCFNumber")]) {
            str = [NSString stringWithFormat:@"@property (nonatomic, assign) int %@;",key];
        }
        if ([obj isKindOfClass:NSClassFromString(@"__NSCFArray")] || [obj isKindOfClass:[NSArray class]]) {
            str = [NSString stringWithFormat:@"@property (nonatomic, strong) NSArray *%@;",key];
        }
        
        if ([obj isKindOfClass:NSClassFromString(@"__NSCFDictionary")] || [obj isKindOfClass:[NSDictionary class]]) {
            str = [NSString stringWithFormat:@"@property (nonatomic, strong) NSDictionary *%@;",key];
        }
        if ([obj isKindOfClass:NSClassFromString(@"__NSCFBoolean")]) {
            str = [NSString stringWithFormat:@"@property (nonatomic, assign) BOOL %@;",key];
        }
        
        [proprety appendFormat:@"\n%@\n",str];
        
        
    }];
    NSLog(@"%@",proprety);
    

}
@end
  • 属性赋值

方法一 可以利用kvc setValuesForKeysWithDictionary的方法
原理:遍历字典的所有key,然后从model里查找属性赋值

#import "JAViewModel.h"

@implementation JAViewModel
+ (instancetype)makeModel:(NSDictionary *)dic
{
    JAViewModel *model = [[JAViewModel alloc] init];
    [model setValuesForKeysWithDictionary:dic];
    return model;
}

//重写父类 避免dic里面有没有定义的属性会crash的情况
- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
       // to do something
}
@end

方法二
原理:利用runtime获取model的属性列表,然后从字典里面取出value给属性赋值

/**
 *  自动给属性赋值
 *
 *  @param dict JSON字典/模型字典
 */
+ (instancetype)setPropertyValuesWithDict:(NSDictionary *)dict
{
    //原理:利用runtime获取model的属性列表,然后从字典里面取出value给属性赋值
    
    // 创建实例对象
    id obj = [[self alloc] init];
    
    // 获取属性列表
    /**
     * class_copyIvarList(Class cls, unsigned int *outCount)  获取成员变量列表
     * class 获取那个类的属性
     * outCount 获取的属性总个数
     */
    unsigned int count = 0;
    Ivar *ivarList = class_copyIvarList(self, &count);
    
    //遍历属性列表
    for (int i = 0; i < count; i ++) {
        Ivar aivar = ivarList[i];
        
        //获取属性名字(带下划线)
        NSString *_propertyName = [NSString stringWithUTF8String:ivar_getName(aivar)];
        
        //获取属性type
        NSString *propertyType = [NSString stringWithUTF8String:ivar_getTypeEncoding(aivar)];
        
        //属性名字 不带下划线
        NSString *key = [_propertyName substringFromIndex:1];
        
        //通过属性名从字典里面取出value
        id  value = [dict objectForKey:key];
        
        /*二级model*/
        //当value时字典,并且属性是自定义的model,把字典(value)转换成model
        //当propertyType是自定义的model 那么此时 propertyType = @"@\"AddressModel\"",所以我们要截取字符串,把自定义的model名字取出来
        
        NSString *nsdictStr = @"@\"NSDictionary\"";
        if ([value isKindOfClass:[NSDictionary class] ] && ![propertyType isEqualToString:nsdictStr]) {
            NSRange range = [propertyType rangeOfString:@"\""];
            propertyType = [propertyType substringFromIndex:range.location + range.length];
            range = [propertyType rangeOfString:@"\""];
            propertyType = [propertyType substringToIndex:range.location];
            
            Class modelClass = NSClassFromString(propertyType);
            
            if (modelClass) {
                NSLog(@"propertyType == %@",propertyType);
                value = [modelClass setPropertyValuesWithDict:value];
            }
            
        }
        
        if (value) {
            [obj setValue:value forKey:key];
        }
        
        
    }
    
    return obj;
}

demo: https://github.com/jiayiwei/DictWithModel

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • KVC(Key-value coding)键值编码,单看这个名字可能不太好理解。其实翻译一下就很简单了,就是指iO...
    黑暗中的孤影阅读 49,999评论 74 441
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,219评论 30 472
  • 我曾做过很多次选择,也被选择过很多,由于四年前的一次迷糊与偶然,现在我在这里,浙大真的很美,来到这里快三个...
    洛青禾阅读 372评论 0 3
  • 我在镜花水月里 读你我在高高的云上爱你我在十五的月亮上 等你我借牛郎织女的鹊桥期待与你重逢想穿越这时间,这空间穿越...
    云殇_阅读 163评论 0 2
  • 一夜清香落入怀, 冷风难晓醉归塞。 语不休, 眸望天, 待风来。 古刹剩留残话语, 幽深孤影等谁猜。 莫轻愁, 情...
    沐灬颜阅读 226评论 1 2