1 Star 1 Fork 0

宝东/FBdCache

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
FBDCaheManager.m 3.05 KB
一键复制 编辑 原始数据 按行查看 历史
宝东 提交于 2016-09-28 11:23 . 主要的缓存类
//
// FBDCaheManager.m
// EDCsfzs
//
// Created by feng on 16/9/21.
// Copyright © 2016年 牛高航. All rights reserved.
//
#import "FBDCaheManager.h"
#import "NSString+Base64.m"
#import "BDFilePathTool.h"
static FBDCaheManager* sigleTan;
static NSInteger MAXCACHETIME=60*60*24*10; //设置缓存的最大时间
@implementation FBDCaheManager
{
NSFileManager* _fm;
}
/**
单例的快速创建
@return 工具类单例
*/
+(instancetype)defaultTools
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sigleTan=[[self alloc] init];
sigleTan.countLimit=100;
sigleTan->_fm=[NSFileManager defaultManager];
});
return sigleTan;
}
//存值
-(void)fbdCacheSetObject:(id)data forKey:(NSString*)key
{
if (data&&key)
{
key=[key base64EncodedString];
//先存内存中
NSData*resultData=[NSKeyedArchiver archivedDataWithRootObject:data];
[self setObject:resultData forKey:key];
//再存disk中
NSString *filename = [BD_CacheDir stringByAppendingPathComponent:key];
BOOL isDir = YES;
if (![_fm fileExistsAtPath:BD_CacheDir isDirectory:&isDir]) {
[_fm createDirectoryAtPath:BD_CacheDir withIntermediateDirectories:NO attributes:nil error:nil];
}
NSError *error;
@try {
[resultData writeToFile:filename options:NSDataWritingAtomic error:&error];
}
@catch (NSException * e) {
//TODO: error handling maybe
}
}
}
//取值
-(id)fbdCacheObjectForKey:(NSString*)key
{
key=[key base64EncodedString];
NSString* filePath=[BD_CacheDir stringByAppendingPathComponent:key];
//先从内存中取
NSData* resultData=[self objectForKey:key];
//再从disk中取
if(!resultData)
{
if ([_fm fileExistsAtPath:filePath])
{
NSDate *modificationDate = [[_fm attributesOfItemAtPath:filePath error:nil] objectForKey:NSFileModificationDate];
//如果超过缓存的最大保留时间就删除缓存
if ([modificationDate timeIntervalSinceNow]>MAXCACHETIME)
{
[_fm removeItemAtPath:filePath error:nil];
return nil;
}
resultData=[NSData dataWithContentsOfFile:filePath];
}
else
{
return nil;
}
}
id unArchResult=[NSKeyedUnarchiver unarchiveObjectWithData:resultData];
if (unArchResult) {
return unArchResult;
}
return nil;
}
//清缓存
-(void)fbdClearCache
{
//先把内存清除
[self removeAllObjects];
//再把disk清除
NSError*error=nil;
if ([_fm fileExistsAtPath:BD_CacheDir])
{
[_fm removeItemAtPath:BD_CacheDir error:&error];
if (error) {
NSLog(@"%s fengbaodong:Error log is %@ ",__func__ ,error.localizedDescription);
}
}
}
//计算缓存大小
-(float)fbdGetCacheSize
{
float sizeDir=[BDFilePathTool getDirSizeAtPath:BD_CacheDir];
return sizeDir;
}
@end
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Objective-C
1
https://gitee.com/donggehaoya/FBdCache.git
git@gitee.com:donggehaoya/FBdCache.git
donggehaoya
FBdCache
FBdCache
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385