#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 创建文件管理类
NSFileManager *fileManger = [NSFileManager defaultManager];
NSString *myPath = [self myPath:@"requestDate.archive"];
if (![fileManger fileExistsAtPath:[self myPath:nil]]) { //判断指定的文件路径是否存在
// 返回值YES表示创建目录成功
if ([fileManger createDirectoryAtPath:[self myPath:nil] withIntermediateDirectories:YES attributes:nil error:nil]) {
//使用NSKeyedArchiver的类方法将该NSDate归档成requestDate.archive(这个文件名可以任意指定)。
[NSKeyedArchiver archiveRootObject:[NSDate date] toFile:myPath];
}
}
NSString *path = [self myPath:@"requestDate.archive"]; //获取保存的文件路径
if ([fileManger fileExistsAtPath:path]) { //如果有此路径
/* 1. 恢复指定的文件名对象
NSDate *requestDate = [NSKeyedUnarchiver unarchiveObjectWithFile:path]; */
// 或者 2. 取出文件字典的NSFileCreationDate key,对应的值是文件创建的时间
NSDate *requestDate = [[NSFileManager defaultManager] attributesOfItemAtPath:myPath error:nil][@"NSFileCreationDate"];
NSLog(@"已经过去%f秒",[requestDate timeIntervalSinceNow]);
/*
获取一个date与当前date的时间差,假设requestDate是100,当前date是160。
100 - 160 = -60; 到-61时已经小于-60 */
if ([requestDate timeIntervalSinceNow] < -60) {
NSLog(@"已经过去一分钟...");
// 重新保存当前时间
[NSKeyedArchiver archiveRootObject:[NSDate date] toFile:myPath];
}
}
}
// 设置文件路径
- (NSString *)myPath:(NSString *)childPath {
NSString *myPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"appData"] stringByAppendingPathComponent:childPath];
return myPath;
}
@end