用字典给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键值替换的更多相关文章

  1. 用字典给Model赋值

    用字典给Model赋值 此篇教程讲述通过runtime扩展NSObject,可以直接用字典给Model赋值,这是相当有用的技术呢. 源码: NSObject+Properties.h 与 NSObje ...

  2. 【转】kubernetes 中 deployment 支持哪些键值

    这个比较全,可以参考 ================= https://www.addops.cn/post/kubernetes-deployment-fileds.html ========== ...

  3. java 把json对象中转成map键值对

    相关:Json对象与Json字符串的转化.JSON字符串与Java对象的转换 本文的目的是把json串转成map键值对存储,而且只存储叶节点的数据 比如json数据如下: {responseHeade ...

  4. 如何将Map键值的下划线转为驼峰

    本文不再更新,可能存在内容过时的情况,实时更新请移步我的新博客:如何将Map键值的下划线转为驼峰: 例,将HashMap实例extMap键值下划线转为驼峰: 代码: HashMap<String ...

  5. Java Map 键值对排序 按key排序和按Value排序

    一.理论准备 Map是键值对的集合接口,它的实现类主要包括:HashMap,TreeMap,Hashtable以及LinkedHashMap等. TreeMap:基于红黑树(Red-Black tre ...

  6. 枚举类返回Map键值对,绑定到下拉框

    有时候,页面的下拉框要显示键值对,但是不想从数据库取,此时我们可以写一个枚举类, Java后台代码 1.枚举类 import java.util.HashMap; import java.util.M ...

  7. 根据map键值对,生成update与select语句,单条执行语句

    方法 constructUpdateSQL private static String constructUpdateSQL(String tableName, List<Map<Stri ...

  8. vue中如果在页面中v-model的是字典,那么在定义字典的时候,需要明确定义键值为''或者[],否则给字典的键值赋值后页面不显示

    如题 在template模板中 {{}} {{form_temp.blOwnerMemberList}} #是字典的形式哦 {{}} 在return的属性中 form_temp: { blOwnerM ...

  9. list转map 键值对

    Map<Long,Account> map = new HashMap<Long,Account>(); for(int i=0;i<list.size();i++){ ...

随机推荐

  1. hibernate原生sql封装,报错信息:could not find setter for rownum_

    今天用hibernate的时候,用了一个原生态sql做了一个分页查询,结果就报错了... 找到解决方法了:http://shmily2038.iteye.com/blog/1704963

  2. php中接收参数,不论是来自GET还是POST方法

    不多说,直接上代码, 其实也就是先用GET的方法去获取,如果值为空,在用POST方法去获取 写下来是为了方便和备忘 function getParam($str){       if ( isset( ...

  3. C++运行时动态类型

    RTTI 运行时类型识别(RTTI)的引入有三个作用: 配合typeid操作符的实现: 实现异常处理中catch的匹配过程: 实现动态类型转换dynamic_cast typeid操作符的实现 静态类 ...

  4. Golang 并发Groutine实例解读(二)

    go提供了sync包和channel机制来解决协程间的同步与通信. 一.sync.WaitGroup sync包中的WaitGroup实现了一个类似任务队列的结构,你可以向队列中加入任务,任务完成后就 ...

  5. hadoop学习笔记(十):MapReduce工作原理(重点)

    一.MapReduce完整运行流程 解析: 1 在客户端启动一个作业. 2 向JobTracker请求一个Job ID. 3 将运行作业所需要的资源文件复制到HDFS上,包括MapReduce程序打包 ...

  6. 关于webapi加入Route引用出现问题的解决方案

    首先在程序包管理器控制台运行安装MVC5.0,因为[Route("/api/..")]只会存在于MVC5.0中间,运行  Install-Package Microsoft.Asp ...

  7. Servlet的数据库访问

    创建数据库:   import java.sql.*; public class SqlUtil { static { try { Class.forName("com.mysql.jdbc ...

  8. 【原】通过Dubbo注解实现RPC调用

    启动Dubbo服务有2个方式,1是通过xml配置,2是通过注解来实现,这点和Spring相似. 采用XML配置如下: <?xml version="1.0" encoding ...

  9. commons-fileupload-1.4使用及问题

    文件上传 使用commons-fileupload-1.4控件及依赖的commons-io-2.6控件 jsp页面中内容 <form action="../servlet/FileUp ...

  10. Java Tools &Tools APIs

    java 启动Java应用程序 javac Java编译器javac读取用Java编写的源文件,并将它们编译为字节码类文件. 用法: javac <options> <source ...