NSObject+Property.m 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. //
  2. // NSObject+Property.m
  3. // RuntimeDemo
  4. //
  5. // Created by LeeJay on 16/8/9.
  6. // Copyright © 2016年 LeeJay. All rights reserved.
  7. // 代码下载地址https://github.com/leejayID/Linkage
  8. #import "NSObject+Property.h"
  9. #import <objc/runtime.h>
  10. @implementation NSObject (Property)
  11. + (instancetype)objectWithDictionary:(NSDictionary *)dictionary
  12. {
  13. id obj = [[self alloc] init];
  14. // 获取所有的成员变量
  15. unsigned int count;
  16. Ivar *ivars = class_copyIvarList(self, &count);
  17. for (unsigned int i = 0; i < count; i++)
  18. {
  19. Ivar ivar = ivars[i];
  20. // 取出的成员变量,去掉下划线
  21. NSString *ivarName = [NSString stringWithUTF8String:ivar_getName(ivar)];
  22. NSString *key = [ivarName substringFromIndex:1];
  23. id value = dictionary[key];
  24. // 当这个值为空时,判断一下是否执行了replacedKeyFromPropertyName协议,如果执行了替换原来的key查值
  25. if (!value)
  26. {
  27. if ([self respondsToSelector:@selector(replacedKeyFromPropertyName)])
  28. {
  29. NSString *replaceKey = [self replacedKeyFromPropertyName][key];
  30. value = dictionary[replaceKey];
  31. }
  32. }
  33. // 字典嵌套字典
  34. if ([value isKindOfClass:[NSDictionary class]])
  35. {
  36. NSString *type = [NSString stringWithUTF8String:ivar_getTypeEncoding(ivar)];
  37. NSRange range = [type rangeOfString:@"\""];
  38. type = [type substringFromIndex:range.location + range.length];
  39. range = [type rangeOfString:@"\""];
  40. type = [type substringToIndex:range.location];
  41. Class modelClass = NSClassFromString(type);
  42. if (modelClass)
  43. {
  44. value = [modelClass objectWithDictionary:value];
  45. }
  46. }
  47. // 字典嵌套数组
  48. if ([value isKindOfClass:[NSArray class]])
  49. {
  50. if ([self respondsToSelector:@selector(objectClassInArray)])
  51. {
  52. NSMutableArray *models = [NSMutableArray array];
  53. NSString *type = [self objectClassInArray][key];
  54. Class classModel = NSClassFromString(type);
  55. for (NSDictionary *dict in value)
  56. {
  57. id model = [classModel objectWithDictionary:dict];
  58. [models addObject:model];
  59. }
  60. value = models;
  61. }
  62. }
  63. if (value)
  64. {
  65. [obj setValue:value forKey:key];
  66. }
  67. }
  68. // 释放ivars
  69. free(ivars);
  70. return obj;
  71. }
  72. @end