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);}
阅读全文
0 0
- RunTime应用--数据模型转换
- runtime 创建数据模型
- 数据模型转换
- iOS双层数据模型转换
- runtime实现数据模型,自动绑定数据
- runtime应用
- Runtime-字模转换
- Runtime类的应用
- Runtime的简单应用
- Runtime类基本应用
- runtime实际应用
- Runtime简单应用
- ios runtime基础应用
- Runtime类的应用
- runtime应用一例
- Runtime基础应用
- runtime 实际应用汇总
- iOS中的runtime应用
- 连续子数组的最大和
- linux下查看本机外网ip
- 利用R整合数据
- 定时ajax获取日志(easyui进度条+js滚动条)
- 面向对象的三大特性之多态-java版
- RunTime应用--数据模型转换
- 【poj】 2480 Longge's problem (欧拉函数)
- Gson封装
- Codeforces Round #426 (Div. 2) D. The Bakery(DP+线段树维护)
- 在cmd下运行Python脚本+如何使用Python Shell
- 解决python3 UnicodeEncodeError: 'gbk' codec can't encode character '\xXX' in position XX 标签: pythonco
- HDU
- vim常用操作
- (转)gzib等压缩算法原理详解