用字典给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++){ ...
随机推荐
- elasticsearch(三) 之 elasticsearch目录介绍和配置文件详解
目录 elasticsearch 配置 目录详情 (config) 配置文件 elasticsearch.yml 配置集群名称(cluster.name) 配置 network.host 更改数据和储 ...
- springboot 常用插件
热部署 使用run as -java application, 把spring-loader-1.2.4.RELEASE.jar下载下来,放到项目的lib目录中,然后把IDEA的run参数里VM参数设 ...
- 布局管理器之CardLayout(卡片布局管理器)
对于选项卡这个概念大家可能不会陌生,就是在一个窗口中可以切换显示多页不同的内容,但同一时间只能是其中的某一页可见的,这样的一个个的页面就是选项卡. CardLayout就是类似的这样一个布局管理器,它 ...
- [WC 2018]州区划分
Description 题库链接 小 \(S\) 现在拥有 \(n\) 座城市,第 \(i\) 座城市的人口为 \(w_i\) ,城市与城市之间可能有双向道路相连. 现在小 \(S\) 要将这 \(n ...
- Spring Framework’s WebDataBinder
Last week, I was just outside our nation’s capital teaching Spring Web MVC Framework to a wonderful ...
- c#基础学习(0806)之可变参数、ref和out关键字的简单使用
params可变参数: 1.无论方法有几个参数,可变参数必须出现再参数列表的最后,可以为可变参数直接传递一个对应类型的数组: 2.可变参数可以传递参数也可以不传递参数,如果不传递参数,则数组为一个长度 ...
- K:伸展树(splay tree)
伸展树(Splay Tree),也叫分裂树,是一种二叉排序树,它能在O(lgN)内完成插入.查找和删除操作.在伸展树上的一般操作都基于伸展操作:假设想要对一个二叉查找树执行一系列的查找操作,为了使 ...
- K8S基础概念
一.核心概念 1.Node Node作为集群中的工作节点,运行真正的应用程序,在Node上Kubernetes管理的最小运行单元是Pod.Node上运行着Kubernetes的Kubelet.kube ...
- bzoj3167 [Heoi2013]Sao
传送门 这题神坑啊……明明是你菜 首先大家都知道原题等价于给每个点分配一个$1$~$n$且两两不同的权值,同时还需要满足一些大于/小于关系的方案数. 先看一眼数据范围,既然写明了$n\le 1000$ ...
- UVAlive6800The Mountain of Gold?(负环)
题意 题目链接 问从\(0\)出发能否回到\(0\)且边权为负 Sol 先用某B姓算法找到负环,再判一下负环上的点能否到\(0\) #include<bits/stdc++.h> #def ...