前言
最近閱讀 YYCache和SDImageCache源碼恕刘,學(xué)到了挺多東西峻凫,為了驗(yàn)證學(xué)習(xí)結(jié)果愕撰,模仿寫了AWCache矮湘。
內(nèi)存緩存實(shí)現(xiàn)方案
SDImageCache:NSCache+weakCache
YYCache:雙鏈表+ NSDictionary
AWCache:NSCache+weakCache
磁盤緩存實(shí)現(xiàn)方案
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
總結(jié)
YYCache豐富和強(qiáng)大
SDImageCache簡單好用
源碼地址
https://github.com/molangwu/AWCache
參考文獻(xiàn)
https://github.com/ibireme/YYKit
https://github.com/SDWebImage/SDWebImage