EGOCache 緩存框架詳細(xì)講解


平常大多用SDWebimage做圖片的緩存,如果做語(yǔ)音聊天SDWebimage就不太夠用
,所以推薦用EGOCache做文件緩存。
EGOCache采用磁盤(pán)存儲(chǔ)方式存儲(chǔ),如果文件使用頻率很高可以緩存到內(nèi)存中,減少io操作。


1.EGOCache 作用

EGOCache可以緩存實(shí)現(xiàn)了<NSCodeing>協(xié)議的對(duì)象、圖片、語(yǔ)音、plist文件

2.EGOCache 安裝

pod 'EGOCache', '~> 2.1.3'

3.EGOCache 使用
/**
  *  創(chuàng)建緩存目錄
  *
  *  @return 緩存目錄
  */
-(NSString *)createCacheDirection
{
//沙盒目錄
NSLog(@"-----%@",NSHomeDirectory());
//Document 文件夾目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathDocuments = [paths objectAtIndex:0];
//創(chuàng)建緩存目錄
NSString *createPath = [NSString stringWithFormat:@"%@/MessageCache", pathDocuments];
// 判斷文件夾是否存在,如果不存在,則創(chuàng)建
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];     

如果不指定緩存路徑,默認(rèn)緩存到library下的cache目錄下

//清除緩存
[egocache clearCache];  

//設(shè)置緩存時(shí)間 默認(rèn)時(shí)間一天  一天的時(shí)間表示:24*60*60
egocache.defaultTimeoutInterval = 60;

緩存文字

//緩存文字
NSString *cacheString = @"111111111111";
[egocache setString:cacheString forKey:@"string"];
//是否有這個(gè)緩存
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) {
    //此處已經(jīng)在主線(xiàn)程了
    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:filePath]];
    
    //拿到圖片后緩存起來(lái)
    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];
    });
}];
//開(kāi)始任務(wù)
[downloadTask resume];
}
讀取圖片
//是否有這個(gè)緩存
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時(shí)遍歷一下當(dāng)前文件日期是否超過(guò)當(dāng)前日期,如果超過(guò)刪除文件
    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源碼

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫(kù)、插件、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 15,410評(píng)論 4 61
  • 1. 今天在公司遇到一件讓我特別生氣的事。 事情的經(jīng)過(guò)是這樣的—— 近期要投一個(gè)非常重要的標(biāo),公司老總對(duì)此非常重視...
    零瓏心閱讀 601評(píng)論 1 14
  • 小胖 文靜的小男孩 話(huà)不多 還害羞 喜歡用眼神與人交流 吃飯有點(diǎn)快 所以有點(diǎn)胖 小胖媽 淳樸又善良 也是不多言 喜...
    若水_086閱讀 481評(píng)論 11 18
  • 身體是革命的本錢(qián),擁有健康的體魄,才能追求更多的自由。要想養(yǎng)好身體,我們可以從飲食和運(yùn)動(dòng)入手。 飲食篇 快餐當(dāng)然也...
    wukaili閱讀 333評(píng)論 0 4
  • 終于在國(guó)慶節(jié)這天將劉奎齡的《花禽十二條屏》圖之一完成了。從開(kāi)始到結(jié)束拖拖拉拉十個(gè)來(lái)月。 這幅作品很多的第一次嘗...
    愛(ài)手工的慧慧閱讀 934評(píng)論 11 17

友情鏈接更多精彩內(nèi)容