用字典给Model赋值
用字典给Model赋值
此篇教程讲述通过runtime扩展NSObject,可以直接用字典给Model赋值,这是相当有用的技术呢。
源码:
NSObject+Properties.h 与 NSObject+Properties.m
//
// NSObject+Properties.h
//
// Created by YouXianMing on 14-9-4.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
//#import <Foundation/Foundation.h>@interface NSObject (Properties)- (void)setDataDictionary:(NSDictionary*)dataDictionary;
- (NSDictionary *)dataDictionary;@end
//
// NSObject+Properties.m
//
// Created by YouXianMing on 14-9-4.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
//#import "NSObject+Properties.h"
#import <objc/runtime.h>@implementation NSObject (Properties)#pragma public - 公开方法- (void)setDataDictionary:(NSDictionary*)dataDictionary
{[self setAttributes:dataDictionary obj:self];
}- (NSDictionary *)dataDictionary
{// 获取属性列表NSArray *properties = [self propertyNames:[self class]];// 根据属性列表获取属性值return [self propertiesAndValuesDictionary:self properties:properties];
}#pragma private - 私有方法// 通过属性名字拼凑setter方法
- (SEL)getSetterSelWithAttibuteName:(NSString*)attributeName
{NSString *capital = [[attributeName substringToIndex:1] uppercaseString];NSString *setterSelStr = \[NSString stringWithFormat:@"set%@%@:", capital, [attributeName substringFromIndex:1]];return NSSelectorFromString(setterSelStr);
}// 通过字典设置属性值
- (void)setAttributes:(NSDictionary*)dataDic obj:(id)obj
{// 获取所有的key值NSEnumerator *keyEnum = [dataDic keyEnumerator];// 字典的key值(与Model的属性值一一对应)id attributeName = nil;while ((attributeName = [keyEnum nextObject])){// 获取拼凑的setter方法SEL sel = [obj getSetterSelWithAttibuteName:attributeName];// 验证setter方法是否能回应if ([obj respondsToSelector:sel]){id value = nil;id tmpValue = dataDic[attributeName];if([tmpValue isKindOfClass:[NSNull class]]){// 如果是NSNull类型,则value值为空value = nil;}else{value = tmpValue;}// 执行setter方法[obj performSelectorOnMainThread:selwithObject:valuewaitUntilDone:[NSThread isMainThread]];}}
}// 获取一个类的属性名字列表
- (NSArray*)propertyNames:(Class)class
{NSMutableArray *propertyNames = [[NSMutableArray alloc] init];unsigned int propertyCount = 0;objc_property_t *properties = class_copyPropertyList(class, &propertyCount);for (unsigned int i = 0; i < propertyCount; ++i){objc_property_t property = properties[i];const char *name = property_getName(property);[propertyNames addObject:[NSString stringWithUTF8String:name]];}free(properties);return propertyNames;
}// 根据属性数组获取该属性的值
- (NSDictionary*)propertiesAndValuesDictionary:(id)obj properties:(NSArray *)properties
{NSMutableDictionary *propertiesValuesDic = [NSMutableDictionary dictionary];for (NSString *property in properties){SEL getSel = NSSelectorFromString(property);if ([obj respondsToSelector:getSel]){NSMethodSignature *signature = nil;signature = [obj methodSignatureForSelector:getSel];NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];[invocation setTarget:obj];[invocation setSelector:getSel];NSObject * __unsafe_unretained valueObj = nil;[invocation invoke];[invocation getReturnValue:&valueObj];//assign to @"" stringif (valueObj == nil){valueObj = @"";}propertiesValuesDic[property] = valueObj;}}return propertiesValuesDic;
}@end
测试用Model
Model.h 与 Model.m
//
// Model.h
// Runtime
//
// Created by YouXianMing on 14-9-5.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
//#import <Foundation/Foundation.h>@interface Model : NSObject@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSNumber *age;
@property (nonatomic, strong) NSDictionary *addressInfo;
@property (nonatomic, strong) NSArray *events;@end
//
// Model.m
// Runtime
//
// Created by YouXianMing on 14-9-5.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
//#import "Model.h"@implementation Model@end
使用时的情形
//
// AppDelegate.m
// Runtime
//
// Created by YouXianMing on 14-9-5.
// Copyright (c) 2014年 YouXianMing. All rights reserved.
//#import "AppDelegate.h"
#import "NSObject+Properties.h"
#import "Model.h"@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{// 初始化modelModel *model = [Model new];// 通过字典赋值model.dataDictionary = @{@"name" : @"YouXianMing",@"age" : @26,@"addressInfo" : @{@"HuBei": @"WeiHan"},@"events" : @[@"One", @"Two", @"Three"]};// 打印出属性值NSLog(@"%@", model.dataDictionary);return YES;
}@end
打印的信息:
2014-09-05 21:03:54.840 Runtime[553:60b] {
addressInfo = {
HuBei = WeiHan;
};
age = 26;
events = (
One,
Two,
Three
);
name = YouXianMing;
}
以下是两段核心代码(符合单一职能):
用字典给Model赋值相关推荐
- iOS UI基础-4.1应用程序管理 字典转Model
用模型取代字典 使用字典的坏处 一般情况下,设置数据和取出数据都使用"字符串类型的key",编写这些key时,编辑器没有智能提示,需要手敲 dict[@"name&quo ...
- 用字典生成model的代码
//用字典生成model的代码 -(void)createModelCodeWithDictionary:(NSDictionary *)dict modelName:(NSString *)mode ...
- python setdefault函数_python中字典中的赋值技巧,update批量更新、比较setdefault方法与等于赋值...
知识回顾: 之前这节主要学习了字典的删除,主要涉及到两个方法: 1. Pop方法:删除指定的键的键值对.需要指定一个自己已知的键,删除后返回的是键对应的值. 2. Popitem方法:删除的是最后一个 ...
- 【iOS开发】字典的快速赋值 setValuesForKeysWithDictionary
前言 在学习解析数据的时候,我们经常是这么写的: PersonModel.h文件中 @property (nonatomic,copy)NSString *name;@property (nonato ...
- Python字典(Dictionary)的setdefault()方法的详解,字典中的赋值技巧
定义 1.字典的setdefault() 方法和 get()方法类似,返回指定键的值,如果键不在字典中,将会添加键值对,值默认为None. 2.setdefault()与get()区别: setdef ...
- 不在被虐中成长就在被虐中死亡
今天又被虐了,哎,平时太不注意细节了算是提了个醒吧,记录下来不要再被绊倒第二次 1.视图完整生命周期,First VC是从xib文件创建的,所以走了initWithCoder 2.判断一个数组是否是有 ...
- 类似索引Model套Model之 iOS模型闲聊二
看下界面, 这是类似于索引的页面, 只不过木有右侧索引条的布局. 如果想了解通讯录索引的,请移步iOS - 高仿通讯录之商品索引排序搜索. 提供思路如下: 分析界面及接口 用 MVC 设计模式来实现( ...
- ASP.NET MVC one view bind many model
一.自定义视图模型 model.cs public class AorBvm{public List<Role> GetRole { get; set; }public List<C ...
- iOS 用runtime封装字典转模型
封装字典转模型: 只需传入model名和json数组,用runtime动态的为每个属性赋值,导入头文件objc/runtime,首先,记录model类中的成员变量数,然后class_copyprope ...
最新文章
- linux中使用u盘和光驱的命令_Linux操作系统下挂载硬盘光驱和U盘的方法
- 如何把PB程序的数据库从ASA迁移到ASE?
- 上海大学c语言程序设计,【基础强化】2020-2021学年秋季学期程序设计C语言项目顺利开展...
- fedora14 an mysql_Fedora 14下 MySQL 更改密码
- springboot打包成jar包后找不到xml,找不到主类的解决方法
- python中常见的流程结构-Python分支结构(switch)操作简介
- 树的先序遍历,中序遍历,后续遍历(递归和非递归实现)
- java 日历选择天_Java程序使用Java日历将天添加到当前日期
- 世界备份日,您的数据足够安全吗?
- RabbitMQ 基本使用(注解的方式)
- 好用的源码行数统计工具——cloc
- stm32f4c语言编程,如何使用STM32F4的DSP库
- 英语语法——名词和名词性从句
- Linux 中实用但很小众的 11 个炫酷终端命令
- Centos7 安装coturn部署一套 STUN/TURN 服务 webRTC打洞服务器
- 百度统计工具是什么?百度统计工具有什么用呢?
- 今天,昆山向全世界发出邀请!
- NRF51822 小黄车智能锁 逆向工程
- 让你的网站支持手机二维码登录
- Spring是什么?关于Spring家族
热门文章
- Apple 的 CEO和Google的CEO在星巴克聊什么呢?
- 究竟哪种取数据的方式最快?
- 修复病毒破坏的文件关联并恢复程序图标
- linux红黑树节点没有数据,真正理解红黑树,真正的(Linux内核里大量用到的数据 -电脑资料...
- 去掉 edittext 长按全选_开封消毒湿巾全选
- 互联网晚报 | 2月21日 星期一 | 北京冬奥会闭幕;天猫将新增菜鸟驿站送货上门服务;上汽奥迪首款电动车型开启预售...
- 互联网晚报 | 2月12日 星期六 | 宝马控股华晨宝马落锤;知乎否认视频部门裁员;《老友记》全十季高清版全网首播...
- 2020中国网络媒体发展报告
- 线下实战—6月25号(深圳)
- 写一函数,使输入的一个字符串按反序存放,在主函数中输入输出反序后的字符串。