#import <Foundation/Foundation.h>
@interface BaseCodingModel : NSObject<NSCoding>
@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;
//手機(jī)號
@property (nonatomic ,copy) NSString * mobile;
//customer_id
@property (nonatomic ,copy) NSString * customer_id;
//token
@property (nonatomic ,copy) NSString * token;
//實(shí)列化
+ (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
//轉(zhuǎn)模型
EPUserModel * user = [EPUserModel sharedUserModel];
user = [EPUserModel mj_objectWithKeyValues:returnValue];
user.isLogin = YES;
//保存用戶信息到本地
[user archive];
//查詢用戶信息
EPUserModel * model = [EPUserModel sharedUserModel];
//退出登錄瓢娜,清除信息
if ([[EPUserModel sharedUserModel] logout]) {
//跳轉(zhuǎn)至主界面
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者