| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- //
- // 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"];
- }
- //解码方法,当把二进制数据转成对象时调用。
- -(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"];
- }
- 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
|