| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- //
- // BaseJosonModel.m
- // IBOSS
- //
- // Created by apple on 2017/7/10.
- // Copyright © 2017年 沈阳东科云信软件有限公司. All rights reserved.
- //
- #import "BaseJosonModel.h"
- #import <objc/runtime.h>
- @implementation BaseJosonModel
- - (id)initWithDictionary:(NSDictionary *)dic
- {
- self = [self init];
- [self setValueWithDictionary:dic obj:self];
- return self;
- }
- - (void)setValueWithDictionary:(NSDictionary *)dic obj:(id)obj
- {
- NSArray *arr = [obj getAllProperties:[obj class]];
- NSArray *propertiesArray = [arr objectAtIndex:0];
- NSArray *kindsArray = [arr objectAtIndex:1];
-
- for (NSInteger i = 0; i < [propertiesArray count]; i++)
- {
- NSString *key = [propertiesArray objectAtIndex:i];
- NSString *kind = [kindsArray objectAtIndex:i];
-
- id value = [dic objectForKey:key];
-
- Class kindClass = NSClassFromString(kind);
- if ([kindClass isSubclassOfClass:[BaseJosonModel class]])
- { // 如果属性为LLJsonModel对象的时候
- // new出对象
- id kindObj = [kindClass new];
- // 将new出的对象赋值给现对象中的对象
- [obj setValue:kindObj forKey:key];
- // 递归进行便利
- [obj setValueWithDictionary:value obj:kindObj];
- } else {
- if (value && [NSNull null] != value)
- {
- [obj setValue:value forKey:key];
- }
- }
- }
- }
- // 获取属性和对象种类
- - (NSArray *)getAllProperties:(Class)class
- {
- u_int count;
- objc_property_t *properties = class_copyPropertyList(class, &count);
- NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
- NSMutableArray *kindsArray = [NSMutableArray arrayWithCapacity:count];
- for (int i = 0; i < count; i++)
- {
- const char *propertyName =property_getName(properties[i]);
- [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
-
- const char *attributes = property_getAttributes(properties[i]);//获取属性类型
- NSString *attr = [NSString stringWithUTF8String: attributes];
- NSString *kind = [[attr componentsSeparatedByString:@","] objectAtIndex:0];
- kind = [kind stringByReplacingOccurrencesOfString:@"T" withString:@""];
- kind = [kind stringByReplacingOccurrencesOfString:@"\"" withString:@""];
- kind = [kind stringByReplacingOccurrencesOfString:@"@" withString:@""];
- [kindsArray addObject:kind];
- }
- free(properties);
-
- return [[NSArray alloc] initWithObjects:propertiesArray, kindsArray, nil];
- }
- @end
|