实现字典和对象转换的工具类
来源:互联网 发布:淘宝ipad横版 编辑:程序博客网 时间:2024/05/22 15:39
#import <Foundation/Foundation.h>@interface EntityHelper : NSObject//字典对象转为实体对象+ (void) dictionaryToEntity:(NSDictionary *)dict entity:(NSObject*)entity;//实体对象转为字典对象+ (NSDictionary *) entityToDictionary:(id)entity;@end
#import "EntityHelper.h"#import <objc/runtime.h>@implementation EntityHelper+ (void) dictionaryToEntity:(NSDictionary *)dict entity:(NSObject*)entity{ if (dict && entity) { for (NSString *keyName in [dict allKeys]) { //构建出属性的set方法 NSString *destMethodName = [NSString stringWithFormat:@"set%@:",[keyName capitalizedString]]; //capitalizedString返回每个单词首字母大写的字符串(每个单词的其余字母转换为小写) SEL destMethodSelector = NSSelectorFromString(destMethodName); if ([entity respondsToSelector:destMethodSelector]) { [entity performSelector:destMethodSelector withObject:[dict objectForKey:keyName]]; } }//end for }//end if}+ (NSDictionary *) entityToDictionary:(id)entity{ Class clazz = [entity class]; u_int count; objc_property_t* properties = class_copyPropertyList(clazz, &count); NSMutableArray* propertyArray = [NSMutableArray arrayWithCapacity:count]; NSMutableArray* valueArray = [NSMutableArray arrayWithCapacity:count]; for (int i = 0; i < count ; i++) { objc_property_t prop=properties[i]; const char* propertyName = property_getName(prop); [propertyArray addObject:[NSString stringWithCString:propertyName encoding:NSUTF8StringEncoding]]; // const char* attributeName = property_getAttributes(prop); // NSLog(@"%@",[NSString stringWithUTF8String:propertyName]); // NSLog(@"%@",[NSString stringWithUTF8String:attributeName]); id value = [entity performSelector:NSSelectorFromString([NSString stringWithUTF8String:propertyName])]; if(value ==nil) [valueArray addObject:[NSNull null]]; else { [valueArray addObject:value]; } // NSLog(@"%@",value); } free(properties); NSDictionary* returnDic = [NSDictionary dictionaryWithObjects:valueArray forKeys:propertyArray];// NSLog(@"%@", returnDic); return returnDic;}@end
0 0
- 实现字典和对象转换的工具类
- 字典库和转换工具
- 树形控件工具类,实现Tree对象和WebFXTree/WebFXTreeItem的转换
- Java 对象和xml转换工具类
- fastJson API 最快的Json和对象转换工具
- 通过QTP的XMLUTIL将XML和字典对象Dictionary之间的互相转换
- Objective-C中ORM的运用:实体对象和字典的相互自动转换
- Objective-C中ORM的运用:实体对象和字典的相互自动转换
- iOS应用开发18——对象和字典之间的转换
- 利用泛型和反射对Java对象集合转换成Json的工具类
- 字符串和字典之间的转换
- 字典和Base64编码的转换
- python字典和JSON格式的转换
- 一个自己编写的xml和JAVA对象之间的转换工具,xml和对象轻松转换(simple-xml2object)
- 实例对象和字典的相互转化
- iOS ~ json、字典和对象的区别
- pix和dip转换的工具类
- Json和JavaBean的转换工具类
- 奔跑吧小子 v1.0.3 安卓版
- OpenCV------- 对XML和YAML文件实现I/O操作
- hdu1021Fibonacci Again
- UIKit类图
- java命令模式
- 实现字典和对象转换的工具类
- js内置对象(概念)
- 当系统内存不足时如何优雅的关闭或退出应用。
- 你应该掌握的七种回归技术
- CQOI2013 棋盘游戏
- 重学Linux——笔记
- 为什么button在设置标题时要用一个方法,而不像lable一样直接用一个属性
- HDU 1249 三角形(平面分割 找规律)
- js内置对象(日期对象)