| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- //
- // ModelUser.m
- // model
- //
- // Created by JuYi on 2018/7/18.
- // Copyright © 2018年 Mine. All rights reserved.
- //
- #import "ModelUser.h"
- // 账号的存储路径
- #define YanCAccountFilePath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"model.data"]
- @implementation ModelUser
- +(ModelUser *)modelUser
- {
- __strong static ModelUser *modelUser;
-
- static dispatch_once_t onceToken;
- dispatch_once(&onceToken, ^{
- modelUser = [[ModelUser alloc] init];
- });
-
- return modelUser;
- }
- //编码方法,当对象被编码成二进制数据时调用。
- -(void)encodeWithCoder:(NSCoder *)aCoder {
- //在编码方法中,需要对对象的每一个属性进行编码。
- [aCoder encodeObject:_pk forKey:@"pk"];
- [aCoder encodeObject:_modelpk forKey:@"modelpk"];
- [aCoder encodeObject:_coin_a forKey:@"coin_a"];
- [aCoder encodeObject:_coin_ir forKey:@"coin_ir"];
- [aCoder encodeObject:_pet forKey:@"pet"];
- }
- //解码方法,当把二进制数据转成对象时调用。
- -(instancetype)initWithCoder:(NSCoder *)aDecoder {
- //如果父类也遵守NSCoding协议,那么需要写self = [super initWithCoder]
- self = [super init];
- if (self) {
- _pk = [aDecoder decodeObjectForKey:@"pk"];
- _modelpk = [aDecoder decodeObjectForKey:@"modelpk"];
- _coin_a = [aDecoder decodeObjectForKey:@"coin_a"];
- _coin_ir = [aDecoder decodeObjectForKey:@"coin_ir"];
- _pet = [aDecoder decodeObjectForKey:@"pet"];
- }
- return self;
- }
- /**
- * 存储帐号
- */
- + (void)save:(ModelUser *)user {
- // 归档 1
- // [NSKeyedArchiver archiveRootObject:user toFile:YanCAccountFilePath];
- //新的方法归档 2
- //准备路径: YanCAccountFilePath
-
- //1:准备存储数据的对象
- NSMutableData *data = [NSMutableData data];
- //2:创建归档对象
- NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
- //3:开始归档
- [archiver encodeObject:user forKey:@"user"];
- //4:完成归档
- [archiver finishEncoding];
- //5:写入文件当中
- [data writeToFile:YanCAccountFilePath atomically:YES];
-
- }
- /**
- * 读取帐号
- */
- + (ModelUser *)user {
- //反归档1
- // YanCBMUser *user = [NSKeyedUnarchiver unarchiveObjectWithFile:YanCAccountFilePath];
- //反归档2
- //准备解档路径
- NSData *myData = [NSData dataWithContentsOfFile:YanCAccountFilePath];
- //创建反归档对象
- NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:myData];
- //反归档
- // YanCBMUser *user = [YanCBMUser new];
-
- ModelUser *user = [unarchiver decodeObjectForKey:@"user"];
- //完成反归档
- [unarchiver finishDecoding];
-
- return user;
- }
- - (void)setValue:(id)value forUndefinedKey:(NSString *)key {
-
- }
- @end
|