用字典给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:] uppercaseString];
NSString *setterSelStr = \
[NSString stringWithFormat:@"set%@%@:", capital, [attributeName substringFromIndex:]];
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:sel
withObject:value
waitUntilDone:[NSThread isMainThread]];
}
}
} // 获取一个类的属性名字列表
- (NSArray*)propertyNames:(Class)class
{
NSMutableArray *propertyNames = [[NSMutableArray alloc] init];
unsigned int propertyCount = ;
objc_property_t *properties = class_copyPropertyList(class, &propertyCount); for (unsigned int i = ; 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 @"" string
if (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
{
// 初始化model
Model *model = [Model new]; // 通过字典赋值
model.dataDictionary = @{@"name" : @"YouXianMing",
@"age" : @,
@"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赋值的更多相关文章

  1. 用字典给Model赋值并支持map键值替换

    用字典给Model赋值并支持map键值替换 这个是昨天教程的升级版本,支持键值的map替换. 源码如下: NSObject+Properties.h 与 NSObject+Properties.m / ...

  2. 字典的快速赋值 setValuesForKeysWithDictionary

    字典的快速赋值 setValuesForKeysWithDictionary ​ 前言 在学习解析数据的时候,我们经常是这么写的:PersonModel.h文件中    @property (nona ...

  3. iOS UI基础-4.1应用程序管理 字典转Model

    用模型取代字典 使用字典的坏处 一般情况下,设置数据和取出数据都使用“字符串类型的key”,编写这些key时,编辑器没有智能提示,需要手敲 dict[@"name"] = @&qu ...

  4. 将JSON字典转换为Model文件

    将JSON字典转换为Model文件 1. 一切尽在不言中 2. 源码 https://github.com/YouXianMing/CreateModelFromJson 3. 说明 如果你还在手动写 ...

  5. 字典和Model的互转

    LHModel的简单使用: LHModel是一个JSON转model,model转JSON的工具类. 使用很多runtime的API.调用简单,真正能用到的只有两个方法. Model* model = ...

  6. 【iOS开发】字典的快速赋值 setValuesForKeysWithDictionary

    前言 在学习解析数据的时候,我们经常是这么写的:PersonModel.h文件中 @property (nonatomic,copy)NSString *name; @property (nonato ...

  7. 总结day5 ---- ,字典的学习,增删改查,以及字典的嵌套, 赋值运算

    内容大纲: 一:字典的定义 二:字典的增加 >1:按照key增加,  无则增加,有则覆盖 >2:setdefault()  ,无则增加,有则不变 三:字典的删除 >1:pop()  ...

  8. 利用特性和反射给泛型Model赋值

    为了解决从数据库读取的表字段和自己建的viewModel字段名称不相符的问题 本人小白,初次将特性及反射应用到实例,写的不好的地方还请大家多多包涵 新建一个控制台应用程序命名为ReflectAndAt ...

  9. TDictionary字典 记录 的赋值。

    type TRen = record age: Integer; //把name定义成结构的属性. private Fname: string; procedure Setname(const Val ...

随机推荐

  1. ActiveMQ HelloWorld入门

    在P2P的消息模型中,双方通过队列交流,一个队列只有一个生产者和一个消费者.a.消息生产者 package com.ljq.durian.test.activemq; import javax.jms ...

  2. springcloud-07-eureka HA的高可用配置

    单机版的eureka, 运行时间稍长, 就会在管理界面出现红色的警告, 为了消除这个警告, 可以使用eureka的高可用配置: 只需要写一个工程配置不同的配置文件, 然后启动多实例即可: 请参照单机版 ...

  3. springboot-8- 日志配置

    1, logback配置 springboot 默认支持logback, 自动加载classpath:logback-spring.xml <!-- logback多文件输出 --> &l ...

  4. Linux中终端和控制台的一些不成熟的理解

    首先声明,这仅仅是在下一些不成熟的想法.是通过看网上的一些资料和自己实践的一些心得,应该都是些很不成熟甚至是不太正确的想法.但是我还是想记录下来,算是一个心路历程吧.等以后成熟了,再来修改. 首先说一 ...

  5. 【云+社区极客说】新一代大数据技术:构建PB级云端数仓实践

    本文来自腾讯云技术沙龙,本次沙龙主题为构建PB级云端数仓实践 在现代社会中,随着4G和光纤网络的普及.智能终端更清晰的摄像头和更灵敏的传感器.物联网设备入网等等而产生的数据,导致了PB级储存的需求加大 ...

  6. JAVA 之 多态 抽象 接口

    一:多态  1:多态   一个对象有多种形式的能力 2:步骤 1编写父类派生子类 2子类重写父类方法 3用父类的数据类型引用子类对象 3:静态多态的实现方式就是方法重载 4:动态多态的实现方式就是重写 ...

  7. 生产环境部署node记录(二):pm2和nginx

    安装完node和npm ,接下来安装pm2 首先简单介绍下pm2,官网的介绍是: pm2 是一个带有负载均衡功能的Node应用的进程管理器.当你要把你的独立代码利用全部的服务器上的所有CPU,并保证进 ...

  8. 区别js中name与id的简单方法

    举个简单的例子: <form name="form1"> 用户名:<input type=text name="username" id=&q ...

  9. bind9配置转发服务

    修改bind主配置文件 $ vi /etc/named.conf//// named.conf//// Provided by Red Hat bind package to configure th ...

  10. [转]SQL SERVER数据库删除LOG文件和清空日志的方案

    本文转自:https://www.cnblogs.com/ShaYeBlog/archive/2012/09/04/2670505.html 数据库在使用过程中会使日志文件不断增加,使得数据库的性能下 ...