口袋优选

HotSearchModel.m 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //
  2. // HotSearchModel.m
  3. // YouHuiProject
  4. //
  5. // Created by 小花 on 2018/10/19.
  6. // Copyright © 2018年 kuxuan. All rights reserved.
  7. //
  8. #import "HotSearchModel.h"
  9. @implementation HotSearchModel
  10. - (void)encodeWithCoder:(NSCoder *)encoder
  11. {
  12. unsigned int count = 0;
  13. // 利用runtime获取实例变量的列表
  14. Ivar *ivars = class_copyIvarList([self class], &count);
  15. for (int i = 0; i < count; i ++) {
  16. // 取出i位置对应的实例变量
  17. Ivar ivar = ivars[i];
  18. // 查看实例变量的名字
  19. const char *name = ivar_getName(ivar);
  20. // C语言字符串转化为NSString
  21. NSString *nameStr = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
  22. // 利用KVC取出属性对应的值
  23. id value = [self valueForKey:nameStr];
  24. // 归档
  25. [encoder encodeObject:value forKey:nameStr];
  26. }
  27. // 记住C语言中copy出来的要进行释放
  28. free(ivars);
  29. }
  30. - (id)initWithCoder:(NSCoder *)decoder
  31. {
  32. if (self = [super init]) {
  33. unsigned int count = 0;
  34. Ivar *ivars = class_copyIvarList([self class], &count);
  35. for (int i = 0; i < count; i ++) {
  36. Ivar ivar = ivars[i];
  37. const char *name = ivar_getName(ivar);
  38. //
  39. NSString *key = [NSString stringWithCString:name encoding:NSUTF8StringEncoding];
  40. id value = [decoder decodeObjectForKey:key];
  41. // 设置到成员变量身上
  42. [self setValue:value forKey:key];
  43. }
  44. free(ivars);
  45. }
  46. return self;
  47. }
  48. @end