用字典给Model赋值并支持map键值替换
用字典给Model赋值并支持map键值替换
这个是昨天教程的升级版本,支持键值的map替换。
源码如下:
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) @property (nonatomic, strong) NSDictionary *mapDictionary; - (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 runtime - 动态添加了一个属性,map属性
static char mapDictionaryFlag;
- (void)setMapDictionary:(NSDictionary *)mapDictionary
{
objc_setAssociatedObject(self, &mapDictionaryFlag, mapDictionary, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSDictionary *)mapDictionary
{
return objc_getAssociatedObject(self, &mapDictionaryFlag);
} #pragma public - 公开方法 - (void)setDataDictionary:(NSDictionary*)dataDictionary
{
[self setAttributes:[self mapDictionary:self.mapDictionary dataDictionary: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;
} // 根据map值替换掉键值
- (NSDictionary *)mapDictionary:(NSDictionary *)map dataDictionary:(NSDictionary *)data
{
if (map && data)
{
// 拷贝字典
NSMutableDictionary *newDataDic = [NSMutableDictionary dictionaryWithDictionary:data]; // 获取所有map键值
NSArray *allKeys = [map allKeys]; for (NSString *oldKey in allKeys)
{
// 获取到value
id value = [newDataDic objectForKey:oldKey]; // 如果有这个value
if (value)
{
NSString *newKey = [map objectForKey:oldKey];
[newDataDic removeObjectForKey:oldKey];
[newDataDic setObject:value forKey:newKey];
}
} return newDataDic;
}
else
{
return data;
}
} @end
注意:
这里给NSObject的category新添加了一个属性,叫mapDictionary
然后给member添加一个属性叫做memberID
以下是使用的情况:
//
// 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]; // 设置map值
model.mapDictionary = @{@"id": @"memberID"}; // 通过字典赋值
model.dataDictionary = @{@"name" : @"YouXianMing",
@"age" : @,
@"addressInfo" : @{@"HuBei": @"WeiHan"},
@"events" : @[@"One", @"Two", @"Three"],
@"id" : @""}; // 打印出属性值
NSLog(@"%@", model.dataDictionary); return YES;
} @end
以下就是使用流程了:
用字典给Model赋值并支持map键值替换的更多相关文章
- 用字典给Model赋值
用字典给Model赋值 此篇教程讲述通过runtime扩展NSObject,可以直接用字典给Model赋值,这是相当有用的技术呢. 源码: NSObject+Properties.h 与 NSObje ...
- 【转】kubernetes 中 deployment 支持哪些键值
这个比较全,可以参考 ================= https://www.addops.cn/post/kubernetes-deployment-fileds.html ========== ...
- java 把json对象中转成map键值对
相关:Json对象与Json字符串的转化.JSON字符串与Java对象的转换 本文的目的是把json串转成map键值对存储,而且只存储叶节点的数据 比如json数据如下: {responseHeade ...
- 如何将Map键值的下划线转为驼峰
本文不再更新,可能存在内容过时的情况,实时更新请移步我的新博客:如何将Map键值的下划线转为驼峰: 例,将HashMap实例extMap键值下划线转为驼峰: 代码: HashMap<String ...
- Java Map 键值对排序 按key排序和按Value排序
一.理论准备 Map是键值对的集合接口,它的实现类主要包括:HashMap,TreeMap,Hashtable以及LinkedHashMap等. TreeMap:基于红黑树(Red-Black tre ...
- 枚举类返回Map键值对,绑定到下拉框
有时候,页面的下拉框要显示键值对,但是不想从数据库取,此时我们可以写一个枚举类, Java后台代码 1.枚举类 import java.util.HashMap; import java.util.M ...
- 根据map键值对,生成update与select语句,单条执行语句
方法 constructUpdateSQL private static String constructUpdateSQL(String tableName, List<Map<Stri ...
- vue中如果在页面中v-model的是字典,那么在定义字典的时候,需要明确定义键值为''或者[],否则给字典的键值赋值后页面不显示
如题 在template模板中 {{}} {{form_temp.blOwnerMemberList}} #是字典的形式哦 {{}} 在return的属性中 form_temp: { blOwnerM ...
- list转map 键值对
Map<Long,Account> map = new HashMap<Long,Account>(); for(int i=0;i<list.size();i++){ ...
随机推荐
- gensim学习笔记
1.词向量建模的word2vec模型和用于长文本向量建模的doc2vec模型 在Gensim中实现word2vec模型非常简单.首先,我们需要将原始的训练语料转化成一个sentence的迭代器:每一次 ...
- 共识算法:PBFT、RAFT
转自:https://www.cnblogs.com/davidwang456/articles/9001331.html 区块链技术中,共识算法是其中核心的一个组成部分.首先我们来思考一个问题:什么 ...
- linux-统计文本中符合条件的内容
1, 单个条件匹配, cat results.log | grep 'status=402' 2, 多个条件匹配 1), 2个条件都要满足 cat results.log | grep "s ...
- Linux中终端和控制台的一些不成熟的理解
首先声明,这仅仅是在下一些不成熟的想法.是通过看网上的一些资料和自己实践的一些心得,应该都是些很不成熟甚至是不太正确的想法.但是我还是想记录下来,算是一个心路历程吧.等以后成熟了,再来修改. 首先说一 ...
- java面试⑤前端部分
2.4.1 简单说一下HTML,CSS,javaScript在网页开发中的定位? 2.4.2简单介绍一下AJAX 2.4.3 JS和JQuery的关系 2.4.4 JQuery的常用选择器 2.4.5 ...
- Zookeeper初见
这是Zookeeper学习总结 的系列文章. ZK简介 ZK部署及运行 ZK的常用API 创建会话 创建节点 删除节点 读取数据节点 更新数据 检测节点是否存在 ZK的开源封装
- C#语法之Linq查询基础二
上篇C#语法之Linq查询基础一基本把Linq介绍了一下,这篇主要是列举下它的几个常见用法. 在用之前先准备些数据,新建了两个类Student.Score,并通过静态方法提供数据. using Sys ...
- sgsdg
wrjow we wetwer werwer werwer werqw qweqwrq qwrqwr @ApiOperation("根据条件分页查询试卷") @ApiRespons ...
- java基础之java的基本数据类型
java分为基本数据类型和引用数据类型.基本数据类型主演分为四类八种,引用数据类型分为接口,类,数组,String. 基本数据类型的四类八种是: 整数类型:byte,short,int,long 数据 ...
- 【1】Singleton模式(单例模式)
一.单例模式的介绍 说到单例模式,大家第一反应应该就是--什么是单例模式?从“单例”字面意思上理解:一个类只有一个实例.所以单例模式也就是保证一个类只有一个实例的一种实现方法罢了(设计模式其实就是帮助 ...