判断文件是否过期并自动删除

判断文件是否过期并自动删除

- (void)deleteExpiredLogFilesByDay:(int)day {
// 通过 NSFileManager 获取文件夹下的文件名列表
    NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:self.folderPath error:nil];  
// 遍历文件列表数组,逐个判断是否过期  
    [fileList enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *filePath = [self.folderPath stringByAppendingPathComponent:obj]; // 拼接文件的绝对路径
        if([self fileIsOutofDate:day inPath:filePath])
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
    }];
}

- (BOOL)fileIsOutofDate:(NSInteger)day inPath:(NSString *)path {
    NSDictionary* fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
    NSDate* fileCreationDate = [fileAttributes objectForKey:@"NSFileCreationDate"];
    NSDate* today = [[NSDate alloc]init];
    // 根据与今日时间间隔秒数的绝对值,判断文件是否过期
    if (fabs([today timeIntervalSinceDate:fileCreationDate]) > day*24*60*60)
        return YES;
    return NO;
}

本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!