swift - YYCache 之 YYDiskCache

YYDiskCache缓存是通过file文件,splits进行数据存储与读取操作,直接放代码

初始化方法:

- (nullable instancetype)initWithPath:(NSString *)path;

- (nullable instancetype)initWithPath:(NSString *)path

                      inlineThreshold:(NSUInteger)threshold

我们看两个方法的实现:

- (instancetype)initWithPath:(NSString *)path {

    return [self initWithPath:path inlineThreshold:1024 * 20]; // 20KB

}


- (instancetype)initWithPath:(NSString *)path

             inlineThreshold:(NSUInteger)threshold {

    self = [super init];

    if (!self) return nil;

    

    YYDiskCache *globalCache = _YYDiskCacheGetGlobal(path);

    if (globalCache) return globalCache;

    

    YYKVStorageType type;

    if (threshold == 0) {

        type = YYKVStorageTypeFile;

    } else if (threshold == NSUIntegerMax) {

        type = YYKVStorageTypeSQLite;

    } else {

        type = YYKVStorageTypeMixed;

    }

    

    YYKVStorage *kv = [[YYKVStorage alloc] initWithPath:path type:type];

    if (!kv) return nil;

    

    _kv = kv;

    _path = path;

    _lock = dispatch_semaphore_create(1);

    _queue = dispatch_queue_create("com.ibireme.cache.disk", DISPATCH_QUEUE_CONCURRENT);

    _inlineThreshold = threshold;

    _countLimit = NSUIntegerMax;

    _costLimit = NSUIntegerMax;

    _ageLimit = DBL_MAX;

    _freeDiskSpaceLimit = 0;

    _autoTrimInterval = 60;

    

    [self _trimRecursively];

    _YYDiskCacheSetGlobal(self);

    

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_appWillBeTerminated) name:UIApplicationWillTerminateNotification object:nil];

    return self;

}

由上可见 initWithPath:方法是调用initWithPath:inlineThreshold:方法创建的disk缓存,disk缓存存在三种缓存策略YYKVStorageTypeFile文件缓存、YYKVStorageTypeSQLite数据库缓存、YYKVStorageTypeMixed混合缓存

- (instancetype)initWithPath:(NSString *)path创建的是默认20KB的混合缓存策略。缓存策略下一个小节去讲述概括

常用的属性:

@property (nullable, copy) NSString *name; // 缓存的名字

@property (readonly) NSString *path;//缓存的位置

@property (readonly) NSUInteger inlineThreshold; //缓存的临界数值用于缓存类型

@property (nullable, copy) NSData *(^customArchiveBlock)(id object); // 块方法归档数据

@property (nullable, copy) id (^customUnarchiveBlock)(NSData *data);// 块方法解归档数据

@property (nullable, copy) NSString *(^customFileNameBlock)(NSString *key); // 自定义文件设置文件名


/*disk缓存操作方法*/

/*是否含有缓存*/

- (BOOL)containsObjectForKey:(NSString *)key;

- (void)containsObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key, BOOL contains))block;


/*获取缓存*/

- (nullable id<NSCoding>)objectForKey:(NSString *)key;

- (void)objectForKey:(NSString *)key withBlock:(void(^)(NSString *key, id<NSCoding> _Nullable object))block;


/*设置缓存*/

- (void)setObject:(nullable id<NSCoding>)object forKey:(NSString *)key;

- (void)setObject:(nullable id<NSCoding>)object forKey:(NSString *)key withBlock:(void(^)(void))block;


/*移除缓存*/

- (void)removeObjectForKey:(NSString *)key;

- (void)removeObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key))block;

- (void)removeAllObjectsWithBlock:(void(^)(void))block;

- (void)removeAllObjectsWithProgressBlock:(nullable void(^)(int removedCount, int totalCount))progress

                                 endBlock:(nullable void(^)(BOOL error))end;

- (void)removeAllObjects;


/*缓存数量*/

- (NSInteger)totalCount;

- (void)totalCountWithBlock:(void(^)(NSInteger totalCount))block;


/*缓存大小*/

- (NSInteger)totalCost;

- (void)totalCostWithBlock:(void(^)(NSInteger totalCost))block;


/*LRU缓存清除*/后期介绍

- (void)trimToCount:(NSUInteger)count;

- (void)trimToCount:(NSUInteger)count withBlock:(void(^)(void))block;

- (void)trimToCost:(NSUInteger)cost;

- (void)trimToCost:(NSUInteger)cost withBlock:(void(^)(void))block;

- (void)trimToAge:(NSTimeInterval)age;

- (void)trimToAge:(NSTimeInterval)age withBlock:(void(^)(void))block;


/*存取对象的扩展数据*/

+ (nullable NSData *)getExtendedDataFromObject:(id)object;

+ (void)setExtendedData:(nullable NSData *)extendedData toObject:(id)object;

使用方法:

func userDiskCache() -> Void {

        var diskPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!

        diskPath += "/DiskCache"

        // 创建默认为20KB的缓存,创建缓存的策略是file于SQlit混合使用

        let diskCache:YYDiskCache = YYDiskCache.init(path: diskPath)!

        diskCache.name = "DiskCacheName"

        /*进行数据缓存*/

        diskCache.setObject("你好" as NSCoding, forKey: "DiskCacheKey")

        /*判断数据缓存*/

        let isContent:Bool = diskCache.containsObject(forKey: "DiskCacheKey")

        print("isContent:\(isContent)")

        /*读取缓存数据*/

        let data:String = diskCache.object(forKey: "DiskCacheKey") as! String

        print("data:\(data)")

        /*获取缓存的数量*/

        let cacheCount:Int = diskCache.totalCount()

        print("cacheCount:\(cacheCount)")

        /*获取缓存的大小*/

        let cacheSize:Int = diskCache.totalCost()

        print("缓存的总体成本cacheSize:\(cacheSize)B")

    }

猜你喜欢

转载自blog.csdn.net/die_word/article/details/80855329