RunTime应用--数据模型转换

来源:互联网 发布:阿里云香港节点ip 编辑:程序博客网 时间:2024/06/05 17:08

创建个Model文件

@interface Model : NSObject@property (copy, nonatomic) NSString *name;@property (copy, nonatomic) NSString *sex;@property (copy, nonatomic) NSString *age;@end
再来个NSObject类别hod

.h

@interface NSObject (hod)+(instancetype) modelWithDict:(NSDictionary *)dic;@end
.m

+(instancetype) modelWithDict:(NSDictionary *)dic{    id object = [[self alloc]init];    //获取属性列表    NSArray *names = [self getPropertyNames];    [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {        if ([names containsObject:key]){            [object setValue:obj forKey:key];        }    }];    return object;}
//获取属性名字+(NSArray *) getPropertyNames{    //先要获取关联对象,如果有值的话直接返回    NSArray *cacheArrs = objc_getAssociatedObject(self, key);    if (cacheArrs){        return cacheArrs;    }    /* 调用运行时方法, 取得类的属性列表 */    /* 成员变量:     * class_copyIvarList(__unsafe_unretained Class cls, unsigned int *outCount)     * 方法:     * class_copyMethodList(__unsafe_unretained Class cls, unsigned int *outCount)     * 属性:     * class_copyPropertyList(__unsafe_unretained Class cls, unsigned int *outCount)     * 协议:     * class_copyProtocolList(__unsafe_unretained Class cls, unsigned int *outCount)     */    unsigned int count = 0; //c数组的下标    objc_property_t *propertyNames = class_copyPropertyList([self class], &count);    NSMutableArray *arrs = [NSMutableArray array];    for (int i=0;i<count;i++){        /* 从数组中取得属性 */        objc_property_t property = propertyNames[i];        /* 从属性中获得属性名称 */        const char *name = property_getName(property);        //转换oc语言        NSString *str = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];        [arrs addObject:str];    }    //设置关联对象    objc_setAssociatedObject(self, key, [arrs copy], OBJC_ASSOCIATION_RETAIN_NONATOMIC);    free(propertyNames);    return [arrs copy];}

绑定一个key值

const char *key = "key";//设置绑定key值
引用库

#import <objc/runtime.h>
调用:

- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    NSDictionary *dic = @{@"name":@"好看",                          @"age":@25,                          @"sex":@"女"                          };    Model *a = [Model modelWithDict:dic];    NSLog(@"%@",a.name);    NSLog(@"%@",a.age);    NSLog(@"%@",a.sex);}