前言
最近阅读 YYCache和SDImageCache源码,学到了挺多东西,为了验证学习结果,模仿写了AWCache。
内存缓存实现方案
SDImageCache:NSCache+weakCache
YYCache:双链表+ NSDictionary
AWCache:NSCache+weakCache
磁盘缓存实现方案
SDImageCache:文件
YYCache:SQLite +文件
AWCache:文件
AWMemoryCache.h
@interface AWMemoryCache<KeyType, ObjectType> : NSCache <KeyType, ObjectType>
@property (nonatomic, class, readonly, nonnull) AWMemoryCache *sharedMemoryCache;
@property (assign, nonatomic) BOOL shouldRemoveAllObjectsOnMemoryWarning;
@property (assign, nonatomic) BOOL shouldRemoveAllObjectsWhenEnteringBackground;
@end
AWDiskCache.h
typedef NS_ENUM(NSUInteger, AWDiskCacheExpireType) {
AWDiskCacheExpireTypeModificationDate,
AWDiskCacheExpireTypeAccessDate,
AWDiskCacheExpireTypeCreationDate
};
@interface AWDiskCache : NSObject
@property (nonatomic, class, readonly, nonnull) AWDiskCache *sharedDiskCache;
@property (nonatomic, assign) NSDataReadingOptions diskCacheReadingOptions;
@property (nonatomic, assign) NSDataWritingOptions diskCacheWritingOptions;
@property (assign, nonatomic) AWDiskCacheExpireType diskCacheExpireType;
@property (nonatomic, assign) NSTimeInterval maxDiskAge;
@property (nonatomic, assign) NSUInteger maxDiskSize;
- (instancetype)init NS_UNAVAILABLE;
- (nullable instancetype)initWithCacheName:(NSString *)name;
- (nullable instancetype)initWithCachePath:(NSString *)cachePath;
- (NSUInteger)totalSize;
- (void)totalSizeWithBlock:(void(^)(NSUInteger))block;
- (NSUInteger)totalCount;
- (void)totalCountWithBlock:(void(^)(NSUInteger))block;
- (nullable NSData *)dataForKey:(NSString *)key;
- (void)dataForKey:(NSString *)key withBlock:(void(^)(NSString *key, NSData * _Nullable data))block;
- (void)setData:(NSData *)data forKey:(NSString *)key;
- (void)setData:(NSData *)data forKey:(NSString *)key withBlock:(nullable void(^)(NSString *key))block;
- (void)removeDataForKey:(NSString *)key;
- (void)removeDataForKey:(NSString *)key withBlock:(nullable void(^)(NSString *key))block;
- (void)removeAllData;
- (void)removeAllDataWithBlock:(nullable void(^)(void))block;
- (void)removeExpiredData;
- (void)removeExpiredDataWithBlock:(nullable void(^)(void))block;
@end
总结
YYCache丰富和强大
SDImageCache简单好用
源码地址
https://github.com/molangwu/AWCache
参考文献
https://github.com/ibireme/YYKit
https://github.com/SDWebImage/SDWebImage