model与dictionary互转

弄了个简单的model与dictionary互转,希望加深对runtime的应用理解。

直接贴代码吧!

#import 

@interface BaseModel : NSObject

//model == > NSDictionary
+ (instancetype)modelWithDict:(NSDictionary *)dict;
//NSDictionary == > model
- (NSDictionary *)modelCoverToDict;

@end
#import "BaseModel.h"
#import //使用runtime需要导入的头文件

@implementation BaseModel

//model == > NSDictionary
+ (instancetype)modelWithDict:(NSDictionary *)dict{
    BaseModel *model = [[[self class] alloc] initWithDict:dict];
    return model;
}

- (instancetype)initWithDict:(NSDictionary *)dict{
    self = [super init];
    if (self) {
        //setValuesForKeysWithDictionary 可通过dict快速赋值
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
    //不需要实现,此方法是防止model中没有对应key导致的崩溃
}

//NSDictionary == > model
- (NSDictionary *)modelCoverToDict{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    //获取到key的值
    unsigned int count = 0;
    objc_property_t *propertyList =  class_copyPropertyList([self class], &count);//获取属性列表
    for (int i = 0; i < count; i ++ ) {
        objc_property_t property = propertyList[i];//取出属性
        const char *property_name = property_getName(property);//获取属性名称
        NSString *key = [NSString stringWithUTF8String:property_name];//转换成NSString
        //获取到key对应value的值
        id value = [self valueForKey:key];
        if (value != nil) {
            [dict setObject:value forKey:key];//设置
        }
    }
    return dict;
}

@end

代码里有注释,其实有runtime基础,很快能看懂的。

然后就是使用过程了,还是直接贴代码:

#import 
#import "BaseModel.h"

@interface UserModel : BaseModel

@property (nonatomic,strong) NSString *name;
@property (nonatomic,strong) NSString *age;

@end

直接继承BaseModel,获得model与dict互转的能力

NSDictionary *dict = @{@"name":@"chen",
                           @"age":@"18",
                           @"intro":@"best"
                           };
//dict == > model
UserModel *model = [UserModel modelWithDict:dict];
NSLog(@"model:  %@ -- %@",model.name,model.age);
//model == > dict
NSLog(@"dict: %@",[model modelCoverToDict]);

这里写的是一级的,如果有二级,可以在setValue: forKey:方法中拦截处理.

 

你可能感兴趣的:(ios,model)