YYCache之《一》磁盘缓存的简单使用

缓存是ios开发中非常常见的,今天就介绍一个优秀的缓存开源库: yycache.
yycache分为两部分:磁盘缓存和内存缓存。
先介绍磁盘缓存:

创建缓存

- (nullable instancetype)initWithPath:(NSString *)path
                      inlineThreshold:(NSUInteger)threshold NS_DESIGNATED_INITIALIZER;

1、路径:路径一旦创建,就是一个只供缓存操作的目录,不能人为读写。
2、yycache的缓存数据存储于sqlite和文件中,由阀值threshold决定,大于阈值的存储于文件,小于等于的存于sqlite.

存储数据
存储操作依赖于YYKVStorage,每一个要存储的数据对应一个YYKVStorageItem

image

YYKVStorageItem的结构如下:

@interface YYKVStorageItem : NSObject
@property (nonatomic, strong) NSString *key;                ///< key
@property (nonatomic, strong) NSData *value;                ///< value
@property (nullable, nonatomic, strong) NSString *filename; ///< filename (nil if inline)
@property (nonatomic) int size;                             ///< value's size in bytes
@property (nonatomic) int modTime;                          ///< modification unix timestamp
@property (nonatomic) int accessTime;                       ///< last access unix timestamp
@property (nullable, nonatomic, strong) NSData *extendedData; ///< extended data (nil if no extended data)
@end

每一条数据不管是否存以文件,都会在数据库中存一条记录。如果是文件的话,inline_data为空。

清除数据
清除数据的策略是根据缓存容量、缓存条目数量、条目存在的时间,三个维度来进行清理。缓存一建立就会起一个后台线程进行轮询清理,轮询间隔是由上层设置,默认是一分钟。

使用缓存
缓存的使用非常简单

//创建
_diskCache  = [[YYDiskCache alloc] initWithPath: [self classroomFilePath]
                                            inlineThreshold:0]; //0代表所有的数据都存储于磁盘
_diskCache.customArchiveBlock   = ^(id object) {return object;};
_diskCache.customUnarchiveBlock = ^(NSData *object) {return object;};

//设置
if (url != nil && url.length != 0 && url1 != nil && url1.path != nil && url1.path.length != 0)
                {
                    [strongSelf1.diskCache setObject:data forKey:url1.path];
                }
//读取
id obj  = [self.diskCache objectForKey:path];

使用时需要注意的是
1、写入和读取的block,默认是archieve,我们可以定义自己的方式,比如直接返回
2、读取和写入文件的路径,可以根据业务的需要,自己来定义路径。

使用就是这些了,下一篇将介绍磁盘缓存内部的实现原理

你可能感兴趣的:(YYCache之《一》磁盘缓存的简单使用)