OC-自动归档存储用户信息

#import 
@interface BaseCodingModel : NSObject
@end
#import "BaseCodingModel.h"

@implementation BaseCodingModel

-(void)setValue:(id)value forUndefinedKey:(NSString *)key {
    
}

//归档
- (void)encodeWithCoder:(NSCoder *)aCoder {
    unsigned int count = 0;
    Ivar * ivarList = class_copyIvarList([self class], &count);
    for (NSInteger i = 0; i < count; i++) {
        Ivar ivar = ivarList[i];
        NSString * key = [NSString stringWithUTF8String:ivar_getName(ivar)];
        id value = [self valueForKey:key];
        [aCoder encodeObject:value forKey:key];
    }
    free(ivarList); //释放指针
}

//解档
- (id)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        unsigned int count = 0;
        Ivar * ivarList = class_copyIvarList([self class], &count);
        for (int i = 0; i < count; i++) {
            Ivar ivar = ivarList[i];
            const char * ivarName = ivar_getName(ivar);
            NSString * key = [NSString stringWithUTF8String:ivarName];
            id value = [aDecoder decodeObjectForKey:key];
            [self setValue:value forKey:key];
        }
        free(ivarList); //释放指针
    }
    return self;
}
@end
#import "BaseCodingModel.h"

@interface UserModel : BaseCodingModel
//是否登录
@property (nonatomic ,assign) BOOL isLogin;
//手机号
@property (nonatomic ,copy) NSString * mobile;

//customer_id
@property (nonatomic ,copy) NSString * customer_id;
//token
@property (nonatomic ,copy) NSString * token;

//实列化
+ (instancetype)sharedUserModel;
//保存
- (BOOL)archive;
//退出
- (BOOL)logout;
@end
#import "UserModel.h"
//document路径
#define DocumentPath NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]
//user归档路径
#define UserArchiveFilePath [NSString stringWithFormat:@"%@/user.data",DocumentPath]

static UserModel * instance = nil;
@implementation UserModel
+ (instancetype)sharedUserModel {
    instance = [NSKeyedUnarchiver unarchiveObjectWithFile:UserArchiveFilePath];
    if (instance == nil) {
        instance = [[EPUserModel alloc] init];
    }
    return instance;
}

- (BOOL)archive {
    return [NSKeyedArchiver archiveRootObject:self toFile:UserArchiveFilePath];
}

- (BOOL)logout {
    return [[NSFileManager defaultManager] removeItemAtPath:UserArchiveFilePath error:NULL];
}
@end
//转模型
EPUserModel * user = [EPUserModel sharedUserModel];
user = [EPUserModel mj_objectWithKeyValues:returnValue];
user.isLogin = YES;
//保存用户信息到本地
[user archive];

//查询用户信息
EPUserModel * model = [EPUserModel sharedUserModel];

//退出登录,清除信息
if ([[EPUserModel sharedUserModel] logout]) {
//跳转至主界面
}

你可能感兴趣的:(OC-自动归档存储用户信息)