iOS之如何判断已经过了多长时间

#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的时间差,假设requestDate100,当前date160

         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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值