EGOCache 缓存框架详细讲解


平常大多用SDWebimage做图片的缓存,如果做语音聊天SDWebimage就不太够用
,所以推荐用EGOCache做文件缓存。
EGOCache采用磁盘存储方式存储,如果文件使用频率很高可以缓存到内存中,减少io操作。


1.EGOCache 作用

EGOCache可以缓存实现了<NSCodeing>协议的对象、图片、语音、plist文件

2.EGOCache 安装

pod 'EGOCache', '~> 2.1.3'

3.EGOCache 使用
/**
  *  创建缓存目录
  *
  *  @return 缓存目录
  */
-(NSString *)createCacheDirection
{
//沙盒目录
NSLog(@"-----%@",NSHomeDirectory());
//Document 文件夹目录
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathDocuments = [paths objectAtIndex:0];
//创建缓存目录
NSString *createPath = [NSString stringWithFormat:@"%@/MessageCache", pathDocuments];
// 判断文件夹是否存在,如果不存在,则创建
if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
    NSFileManager *fileManager = [[NSFileManager alloc] init];
   BOOL result = [fileManager createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    if (result) {
        return createPath;
    }else
    {
        return nil;
    }
} else {
    NSLog(@"FileDir is exists.");
    return createPath;
}
}  
初始化缓存
//initWithCacheDirectory 指定缓存目录 
  EGOCache *egocache = [[EGOCache globalCache] initWithCacheDirectory:cacheDirectory];     

如果不指定缓存路径,默认缓存到library下的cache目录下

//清除缓存
[egocache clearCache];  

//设置缓存时间 默认时间一天  一天的时间表示:24*60*60
egocache.defaultTimeoutInterval = 60;

缓存文字

//缓存文字
NSString *cacheString = @"111111111111";
[egocache setString:cacheString forKey:@"string"];
//是否有这个缓存
BOOL ishaveCacheFile = [egocache hasCacheForKey:@"string"];
if (ishaveCacheFile) {
    //读取文字
    NSString *currentCacheString = [egocache stringForKey:@"string"];
    NSLog(@"缓存的文字:%@",currentCacheString);
}

缓存图片

先下载图片
   -(void)downloadFileWithURLString:(NSString *)aURLString   withFileName:(NSString *)aCacheName
 {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:aURLString]];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURLSessionDownloadTask *downloadTask  =  [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
    
} destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
    NSURL *downloadURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
    return [downloadURL URLByAppendingPathComponent:[response suggestedFilename]];
    
} completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
    //此处已经在主线程了
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:filePath]];
    
    //拿到图片后缓存起来
    EGOCache *egocache = [EGOCache globalCache];
    [egocache setImage:image forKey:aCacheName];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        int a = [[aCacheName stringByReplacingOccurrencesOfString:@"cache_" withString:@""] intValue];
        CGFloat image_width = 10;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(a*image_width, a*image_width, image_width, image_width)];
        EGOCache *egocache = [EGOCache globalCache];
        imageView.image = [egocache imageForKey:aCacheName];
        [self.view addSubview:imageView];
    });
}];
//开始任务
[downloadTask resume];
}
读取图片
//是否有这个缓存
BOOL ishaveCacheImage = [egocache hasCacheForKey:@"cache_0"];
if (ishaveCacheImage) {
    //读取图片
    UIImage *currentCacheimage = [egocache imageForKey:@"cache_0"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage:currentCacheimage];
    imageView.frame = CGRectMake(0, 0, 100, 100);
    [self.view addSubview:imageView];
    imageView.tag = 10010;
}
清除缓存原理
    //每次初始化EGOCache时遍历一下当前文件日期是否超过当前日期,如果超过删除文件
    NSTimeInterval now = [[NSDate date] timeIntervalSinceReferenceDate];
    NSMutableArray* removedKeys = [[NSMutableArray alloc] init];
    
    for(NSString* key in _cacheInfo) {
        if([_cacheInfo[key] timeIntervalSinceReferenceDate] <= now) {
            [[NSFileManager defaultManager] removeItemAtPath:cachePathForKey(_directory, key) error:NULL];
            [removedKeys addObject:key];
        }
    }
    
    [_cacheInfo removeObjectsForKeys:removedKeys];      
缓存记录的plist文件
在沙盒中的样子
源码下载

EGOCache源码

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,787评论 4 61
  • 1. 今天在公司遇到一件让我特别生气的事。 事情的经过是这样的—— 近期要投一个非常重要的标,公司老总对此非常重视...
    零珑心阅读 3,590评论 1 14
  • 小胖 文静的小男孩 话不多 还害羞 喜欢用眼神与人交流 吃饭有点快 所以有点胖 小胖妈 淳朴又善良 也是不多言 喜...
    若水_086阅读 3,214评论 11 18
  • 身体是革命的本钱,拥有健康的体魄,才能追求更多的自由。要想养好身体,我们可以从饮食和运动入手。 饮食篇 快餐当然也...
    wukaili阅读 2,047评论 0 4
  • 终于在国庆节这天将刘奎龄的《花禽十二条屏》图之一完成了。从开始到结束拖拖拉拉十个来月。 这幅作品很多的第一次尝...
    爱手工的慧慧阅读 4,367评论 11 17

友情链接更多精彩内容