ObjectCoder.m 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. //
  2. // ObjectCoder.m
  3. // XMEye
  4. //
  5. // Created by XM on 2018/4/6.
  6. // Copyright © 2018年 Megatron. All rights reserved.
  7. //
  8. #import "ObjectCoder.h"
  9. #import <objc/runtime.h>
  10. @interface ObjectCoder ()
  11. {
  12. NSMutableArray *coderArray;
  13. }
  14. @end
  15. @implementation ObjectCoder
  16. // NSCopying
  17. - (id)copyWithZone:(NSZone *)zone {
  18. [self getAllProperties];
  19. if (coderArray == nil || coderArray.count == 0) {
  20. return self;
  21. }
  22. ObjectCoder *copy = [[[self class] alloc] init];
  23. for (int i =0; i<coderArray.count; i++) {
  24. id value = [self valueForKey:[coderArray objectAtIndex:i]];
  25. if ([value isKindOfClass:[NSArray class]]) {
  26. value = [[NSMutableArray alloc] initWithArray:(NSMutableArray*)value copyItems:YES];
  27. }
  28. [copy setValue:value forKey:[coderArray objectAtIndex:i]];
  29. }
  30. return copy;
  31. }
  32. - (id)mutableCopyWithZone:(nullable NSZone *)zone {
  33. [self getAllProperties];
  34. if (coderArray == nil || coderArray.count == 0) {
  35. return self;
  36. }
  37. ObjectCoder *copy = [[[self class] alloc] init];
  38. for (int i =0; i<coderArray.count; i++) {
  39. id value = [self valueForKey:[coderArray objectAtIndex:i]];
  40. [copy setValue:value forKey:[coderArray objectAtIndex:i]];
  41. }
  42. return copy;
  43. }
  44. //对变量编码
  45. - (void)encodeWithCoder:(NSCoder *)coder {
  46. [self getAllProperties];
  47. if (coderArray == nil || coderArray.count == 0) {
  48. return;
  49. }
  50. for (int i =0; i<coderArray.count; i++) {
  51. id value = [self valueForKey:[coderArray objectAtIndex:i]];
  52. [coder encodeObject:value forKey:[coderArray objectAtIndex:i]];
  53. }
  54. }
  55. //对变量解码
  56. - (id)initWithCoder:(NSCoder *)coder {
  57. self = [super init];
  58. [self getAllProperties];
  59. if (coderArray == nil || coderArray.count == 0) {
  60. return self;
  61. }
  62. for (int i =0; i<coderArray.count; i++) {
  63. id value = [coder decodeObjectForKey:[coderArray objectAtIndex:i]];
  64. if (value != nil) {
  65. [self setValue:value forKey:[coderArray objectAtIndex:i]];
  66. }
  67. }
  68. return self;
  69. }
  70. //获取所有的属性名称字符串
  71. - (NSArray *)getAllProperties {
  72. if (coderArray == nil) {
  73. u_int count;
  74. objc_property_t *properties =class_copyPropertyList([self class], &count);
  75. coderArray = [NSMutableArray arrayWithCapacity:count];
  76. for (int i = 0; i<count; i++){
  77. const char* propertyName =property_getName(properties[i]);
  78. [coderArray addObject: [NSString stringWithUTF8String: propertyName]];
  79. }
  80. free(properties);
  81. }
  82. return coderArray;
  83. }
  84. @end