【objective-c】字典快速转换为Model代码
2015-07-18 17:20
661 查看
一般情况下iOS得局部页面加载的过程是,创建一个Model然后,将Nib文件与Model进行关联,然后能够快速的获取到Nib文件上的控件实例。操作生成页面。
但是原生的内容是没有直接通过Json获取Model只能生成字典。然后转换为Model。下列方法就是通过字典来转换为Model的过程。
将字典转换为Model
复制代码
复制代码
其他两个辅助类型方法
复制代码
复制代码
将Model转换为字典
复制代码
但是原生的内容是没有直接通过Json获取Model只能生成字典。然后转换为Model。下列方法就是通过字典来转换为Model的过程。
将字典转换为Model
复制代码
-(BOOL)reflectDataFromOtherObject:(NSDictionary *)dic { unsigned int outCount, i; objc_property_t *properties = class_copyPropertyList([self class], &outCount); for (i = 0; i < outCount; i++) { objc_property_t property = properties[i]; NSString *propertyName = [[NSString alloc] initWithCString:property_getName(property) encoding:NSUTF8StringEncoding]; NSString *propertyType = [[NSString alloc] initWithCString:property_getAttributes(property) encoding:NSUTF8StringEncoding]; if ([[dic allKeys] containsObject:propertyName]) { id value = [dic valueForKey:propertyName]; if (![value isKindOfClass:[NSNull class]] && value != nil) { if ([value isKindOfClass:[NSDictionary class]]) { id pro = [self createInstanceByClassName:[self getClassName:propertyType]]; [pro reflectDataFromOtherObject:value]; [self setValue:pro forKey:propertyName]; }else{ [self setValue:value forKey:propertyName]; } } } } free(properties); return true; }
复制代码
其他两个辅助类型方法
复制代码
-(NSString *)getClassName:(NSString *)attributes { NSString *type = [attributes substringFromIndex:[attributes rangeOfRegex:@"\""].location + 1]; type = [type substringToIndex:[type rangeOfRegex:@"\""].location]; return type; } -(id) createInstanceByClassName: (NSString *)className { NSBundle *bundle = [NSBundle mainBundle]; Class aClass = [bundle classNamed:className]; id anInstance = [[aClass alloc] init]; return anInstance; }
复制代码
将Model转换为字典
复制代码
-(NSDictionary *)convertModelToDictionary { NSMutableDictionary *dic = [[NSMutableDictionary alloc] init]; for (NSString *key in [self propertyKeys]) { id propertyValue = [self valueForKey:key]; //该值不为NSNULL,并且也不为nil [dic setObject:propertyValue forKey:key]; } return dic; }
相关文章推荐
- OC学习笔记之OC内存管理
- NSArray利用Cocoa框架进行汉字排序
- json格式正确却无法转换成 JSONObject
- NSArray进行汉字排序
- Cordys JAVA Object理解
- Objective-C内存管理(四)@property相关参数详解
- Java常用类源码探究(一):Object类
- Objective-C学习笔记
- Object-C KVC模式使用详解(一)
- syscolumns、sysconstraints、sysobjects
- Objective-C中可变与不可变字符串的学习
- 【objective-c】类目 延展 协议
- Objective-C入门篇
- 【objective-c】内存管理原则
- objectOutputStream
- ObjectOutputStream
- 在一个项目中同时使用Swift和Objective-C代码混合编程的方法
- JsonObject 处理日期
- 一个对象toString()方法如果没有被重写,那么默认调用它的父类Object的toString()方法,而Object的toString()方法是打印该对象的hashCode,一般hashCode就是此对象的内存地址
- 关于Object-C 底层实现self isa 的理解