一、创建一个账号类
#import <Foundation/Foundation.h>
@interface IWAccount : NSObject <NSCoding>
@property (nonatomic, copy) NSString *access_token;
@property (nonatomic, strong) NSDate *expiresTime; // 账号的过期时间
// 如果服务器返回的数字很大, 建议用long long(比如主键, ID)
@property (nonatomic, assign) long long expires_in;
@property (nonatomic, assign) long long remind_in;
@property (nonatomic, assign) long long uid;
+ (instancetype)accountWithDict:(NSDictionary *)dict;
- (instancetype)initWithDict:(NSDictionary *)dict;
@end
#import "IWAccount.h"
@implementation IWAccount
+ (instancetype)accountWithDict:(NSDictionary *)dict
{
return [[self alloc] initWithDict:dict];
}
- (instancetype)initWithDict:(NSDictionary *)dict
{
if (self = [super init]) {
[self setValuesForKeysWithDictionary:dict];
}
return self;
}
/**
* 从文件中解析对象的时候调
*/
- (id)initWithCoder:(NSCoder *)decoder
{
if (self = [super init]) {
self.access_token = [decoder decodeObjectForKey:@"access_token"];
self.remind_in = [decoder decodeInt64ForKey:@"remind_in"];
self.expires_in = [decoder decodeInt64ForKey:@"expires_in"];
self.uid = [decoder decodeInt64ForKey:@"uid"];
self.expiresTime = [decoder decodeObjectForKey:@"expiresTime"];
}
return self;
}
/**
* 将对象写入文件的时候调用
*/
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:self.access_token forKey:@"access_token"];
[encoder encodeObject:self.expiresTime forKey:@"expiresTime"];
[encoder encodeInt64:self.remind_in forKey:@"remind_in"];
[encoder encodeInt64:self.expires_in forKey:@"expires_in"];
[encoder encodeInt64:self.uid forKey:@"uid"];
}
@end
#import <Foundation/Foundation.h>
@class IWAccount;
@interface IWAccountTool : NSObject
/**
* 存储账号信息
*
* @param account 需要存储的账号
*/
+ (void)saveAccount:(IWAccount *)account;
/**
* 返回存储的账号信息
*/
+ (IWAccount *)account;
@end
#import "IWAccount.h"
#import "IWAccountTool.h"
#define IWAccountFile [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"account.data"]
@implementation IWAccountTool
+ (void)saveAccount:(IWAccount *)account
{
// 计算账号的过期时间
NSDate *now = [NSDate date];
account.expiresTime = [now dateByAddingTimeInterval:account.expires_in];
[NSKeyedArchiver archiveRootObject:account toFile:IWAccountFile];
}
+ (IWAccount *)account
{
// 取出账号
IWAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:IWAccountFile];
// 判断账号是否过期
NSDate *now = [NSDate date];
if ([now compare:account.expiresTime] == NSOrderedAscending) { // 还没有过期
return account;
} else { // 过期
return nil;
}
}
@end