ModelUser.m 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. //
  2. // ModelUser.m
  3. // model
  4. //
  5. // Created by JuYi on 2018/7/18.
  6. // Copyright © 2018年 Mine. All rights reserved.
  7. //
  8. #import "ModelUser.h"
  9. // 账号的存储路径
  10. #define YanCAccountFilePath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"model.data"]
  11. @implementation ModelUser
  12. +(ModelUser *)modelUser
  13. {
  14. __strong static ModelUser *modelUser;
  15. static dispatch_once_t onceToken;
  16. dispatch_once(&onceToken, ^{
  17. modelUser = [[ModelUser alloc] init];
  18. });
  19. return modelUser;
  20. }
  21. //编码方法,当对象被编码成二进制数据时调用。
  22. -(void)encodeWithCoder:(NSCoder *)aCoder {
  23. //在编码方法中,需要对对象的每一个属性进行编码。
  24. [aCoder encodeObject:_pk forKey:@"pk"];
  25. [aCoder encodeObject:_modelpk forKey:@"modelpk"];
  26. [aCoder encodeObject:_coin_a forKey:@"coin_a"];
  27. [aCoder encodeObject:_coin_ir forKey:@"coin_ir"];
  28. }
  29. //解码方法,当把二进制数据转成对象时调用。
  30. -(instancetype)initWithCoder:(NSCoder *)aDecoder {
  31. //如果父类也遵守NSCoding协议,那么需要写self = [super initWithCoder]
  32. self = [super init];
  33. if (self) {
  34. _pk = [aDecoder decodeObjectForKey:@"pk"];
  35. _modelpk = [aDecoder decodeObjectForKey:@"modelpk"];
  36. _coin_a = [aDecoder decodeObjectForKey:@"coin_a"];
  37. _coin_ir = [aDecoder decodeObjectForKey:@"coin_ir"];
  38. }
  39. return self;
  40. }
  41. /**
  42. * 存储帐号
  43. */
  44. + (void)save:(ModelUser *)user {
  45. // 归档 1
  46. // [NSKeyedArchiver archiveRootObject:user toFile:YanCAccountFilePath];
  47. //新的方法归档 2
  48. //准备路径: YanCAccountFilePath
  49. //1:准备存储数据的对象
  50. NSMutableData *data = [NSMutableData data];
  51. //2:创建归档对象
  52. NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
  53. //3:开始归档
  54. [archiver encodeObject:user forKey:@"user"];
  55. //4:完成归档
  56. [archiver finishEncoding];
  57. //5:写入文件当中
  58. [data writeToFile:YanCAccountFilePath atomically:YES];
  59. }
  60. /**
  61. * 读取帐号
  62. */
  63. + (ModelUser *)user {
  64. //反归档1
  65. // YanCBMUser *user = [NSKeyedUnarchiver unarchiveObjectWithFile:YanCAccountFilePath];
  66. //反归档2
  67. //准备解档路径
  68. NSData *myData = [NSData dataWithContentsOfFile:YanCAccountFilePath];
  69. //创建反归档对象
  70. NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:myData];
  71. //反归档
  72. // YanCBMUser *user = [YanCBMUser new];
  73. ModelUser *user = [unarchiver decodeObjectForKey:@"user"];
  74. //完成反归档
  75. [unarchiver finishDecoding];
  76. return user;
  77. }
  78. - (void)setValue:(id)value forUndefinedKey:(NSString *)key {
  79. }
  80. @end