BaseJosonModel.m 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. //
  2. // BaseJosonModel.m
  3. // IBOSS
  4. //
  5. // Created by apple on 2017/7/10.
  6. // Copyright © 2017年 沈阳东科云信软件有限公司. All rights reserved.
  7. //
  8. #import "BaseJosonModel.h"
  9. #import <objc/runtime.h>
  10. @implementation BaseJosonModel
  11. - (id)initWithDictionary:(NSDictionary *)dic
  12. {
  13. self = [self init];
  14. [self setValueWithDictionary:dic obj:self];
  15. return self;
  16. }
  17. - (void)setValueWithDictionary:(NSDictionary *)dic obj:(id)obj
  18. {
  19. NSArray *arr = [obj getAllProperties:[obj class]];
  20. NSArray *propertiesArray = [arr objectAtIndex:0];
  21. NSArray *kindsArray = [arr objectAtIndex:1];
  22. for (NSInteger i = 0; i < [propertiesArray count]; i++)
  23. {
  24. NSString *key = [propertiesArray objectAtIndex:i];
  25. NSString *kind = [kindsArray objectAtIndex:i];
  26. id value = [dic objectForKey:key];
  27. Class kindClass = NSClassFromString(kind);
  28. if ([kindClass isSubclassOfClass:[BaseJosonModel class]])
  29. { // 如果属性为LLJsonModel对象的时候
  30. // new出对象
  31. id kindObj = [kindClass new];
  32. // 将new出的对象赋值给现对象中的对象
  33. [obj setValue:kindObj forKey:key];
  34. // 递归进行便利
  35. [obj setValueWithDictionary:value obj:kindObj];
  36. } else {
  37. if (value && [NSNull null] != value)
  38. {
  39. [obj setValue:value forKey:key];
  40. }
  41. }
  42. }
  43. }
  44. // 获取属性和对象种类
  45. - (NSArray *)getAllProperties:(Class)class
  46. {
  47. u_int count;
  48. objc_property_t *properties = class_copyPropertyList(class, &count);
  49. NSMutableArray *propertiesArray = [NSMutableArray arrayWithCapacity:count];
  50. NSMutableArray *kindsArray = [NSMutableArray arrayWithCapacity:count];
  51. for (int i = 0; i < count; i++)
  52. {
  53. const char *propertyName =property_getName(properties[i]);
  54. [propertiesArray addObject: [NSString stringWithUTF8String: propertyName]];
  55. const char *attributes = property_getAttributes(properties[i]);//获取属性类型
  56. NSString *attr = [NSString stringWithUTF8String: attributes];
  57. NSString *kind = [[attr componentsSeparatedByString:@","] objectAtIndex:0];
  58. kind = [kind stringByReplacingOccurrencesOfString:@"T" withString:@""];
  59. kind = [kind stringByReplacingOccurrencesOfString:@"\"" withString:@""];
  60. kind = [kind stringByReplacingOccurrencesOfString:@"@" withString:@""];
  61. [kindsArray addObject:kind];
  62. }
  63. free(properties);
  64. return [[NSArray alloc] initWithObjects:propertiesArray, kindsArray, nil];
  65. }
  66. @end