NSObject+MJCoding.m 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //
  2. // NSObject+MJCoding.m
  3. // MJExtension
  4. //
  5. // Created by mj on 14-1-15.
  6. // Copyright (c) 2014年 小码哥. All rights reserved.
  7. //
  8. #import "NSObject+MJCoding.h"
  9. #import "NSObject+MJClass.h"
  10. #import "NSObject+MJProperty.h"
  11. #import "MJProperty.h"
  12. @implementation NSObject (MJCoding)
  13. - (void)mj_encode:(NSCoder *)encoder
  14. {
  15. Class clazz = [self class];
  16. NSArray *allowedCodingPropertyNames = [clazz mj_totalAllowedCodingPropertyNames];
  17. NSArray *ignoredCodingPropertyNames = [clazz mj_totalIgnoredCodingPropertyNames];
  18. [clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) {
  19. // 检测是否被忽略
  20. if (allowedCodingPropertyNames.count && ![allowedCodingPropertyNames containsObject:property.name]) return;
  21. if ([ignoredCodingPropertyNames containsObject:property.name]) return;
  22. id value = [property valueForObject:self];
  23. if (value == nil) return;
  24. [encoder encodeObject:value forKey:property.name];
  25. }];
  26. }
  27. - (void)mj_decode:(NSCoder *)decoder
  28. {
  29. Class clazz = [self class];
  30. NSArray *allowedCodingPropertyNames = [clazz mj_totalAllowedCodingPropertyNames];
  31. NSArray *ignoredCodingPropertyNames = [clazz mj_totalIgnoredCodingPropertyNames];
  32. [clazz mj_enumerateProperties:^(MJProperty *property, BOOL *stop) {
  33. // 检测是否被忽略
  34. if (allowedCodingPropertyNames.count && ![allowedCodingPropertyNames containsObject:property.name]) return;
  35. if ([ignoredCodingPropertyNames containsObject:property.name]) return;
  36. id value = [decoder decodeObjectForKey:property.name];
  37. if (value == nil) { // 兼容以前的MJExtension版本
  38. value = [decoder decodeObjectForKey:[@"_" stringByAppendingString:property.name]];
  39. }
  40. if (value == nil) return;
  41. [property setValue:value forObject:self];
  42. }];
  43. }
  44. @end