美文网首页
实现简易缓存功能

实现简易缓存功能

作者: yok_ | 来源:发表于2016-10-26 12:39 被阅读12次

    最近公司项目增加了个需求:为了更好的用户体验,节省用户流量,需要实现离线缓存功能

    针对这个需求临时创建了一个简易的缓存管理类,负责管理缓存,其可对数据进行缓存或从缓存中取出或删除缓存。

    创建缓存目录:

    - (id)init
    {
        if ((self = [super init])) {
            // 创建缓存目录
            NSString* cachesDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
            _directory = [[[cachesDirectory stringByAppendingPathComponent:[[NSBundle mainBundle] bundleIdentifier]] stringByAppendingPathComponent:@"XXXXXX"] copy];
            [[NSFileManager defaultManager]createDirectoryAtPath:_directory withIntermediateDirectories:YES attributes:nil error:NULL];
            
            // 获取后台优先级的、并发的、全局的线程队列
            _diskQueue = dispatch_queue_create("com.XXXXXX.cache", DISPATCH_QUEUE_SERIAL);
            dispatch_queue_t priority = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
      dispatch_set_target_queue(priority, _diskQueue);
    
        }
        return self;
    }
    

    把数据写入缓存:

    
    - (void)setObject:(id)anObject forKey:(NSString*)key
    {   
            NSData *data = [NSKeyedArchiver archivedDataWithRootObject:anObject];  
      
            NSString* cachePath = cachePathForKey(_directory, key);
            dispatch_async(_diskQueue, ^{   
            [data writeToFile:cachePath atomically:YES];    
            });
    }
    
    

    从缓存中取出数据:

    - (id<NSCoding>)objectForKey:(NSString*)key{
        if([self hasCacheForKey:key]) {               
                 NSData *data =  [NSData dataWithContentsOfFile:cachePathForKey(_directory, key) options:0 error:NULL];     
               return [NSKeyedUnarchiver unarchiveObjectWithData:data];
        }else {     
               return nil;  
              }
    }
    

    清除缓存数据:

    - (void)clearAllCache{    
              dispatch_sync(_diskQueue, ^{        
                   NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:_directory];      
                   NSString *fileName;        
                 while (fileName= [dirEnum nextObject]) {    
            [[NSFileManager defaultManager] removeItemAtPath: [NSString stringWithFormat:@"%@/%@",_directory, fileName] error:NULL];                     }  
        });
    }
    

    相关文章

      网友评论

          本文标题:实现简易缓存功能

          本文链接:https://www.haomeiwen.com/subject/iyvduttx.html