pod 'StockPile', '~> 0.0'
此库提供基于 LRU 的缓存。库遵循三种类型的缓存策略
当在崩溃或应用关闭等情况下并不重要保存数据时,应使用内存缓存策略。
当必须保证缓存数据不丢失时,应使用镜像缓存策略。
当在崩溃等情况中丢失数据是可以接受的时候,应使用回退缓存策略。这里的想法是保持数据在可以最快检索的地方。检索顺序是内存 O(1),然后是数据库和磁盘,依此顺序。
库可以通过以下两种方式进行扩展
要创建一个新的算法,请扩展 BaseCache 并实现以下函数
- (BOOL) cacheNode: (Node*) node;
- (Node*) getNodeForKey:(id<NSCopying, NSMutableCopying, NSSecureCoding>) key;
- (void) clearCache;
除非您非常确定自己在做什么,否则不要扩展任何其他方法。
要拥有自己的策略,您需要有一个自己的构建器类。详细信息,请查看 InMemoryDiskCacheBuilder
的代码。
以下代码展示了如何使用 StockPile(使用内存和磁盘复制策略)
//interface for DataSource
@interface DBCacheDataSourceImpl : NSObject<DiskCacheDataSource>
@property (nonatomic) NSInteger pmaximumElementInMemory;
@property (nonatomic) NSInteger pmaximumMemoryAllocated;
@property (nonatomic, copy) NSString* ppathForDiskCaching;
@end
@implementation DBCacheDataSourceImpl
- (NSInteger) maximumElementInMemory;{
return self.pmaximumElementInMemory;
}
- (NSInteger) maximumMemoryAllocated;{
return self.pmaximumMemoryAllocated;
}
- (NSString *)pathForDiskCaching{
return self.ppathForDiskCaching;
}
@end
//setting correct values in data source
DBCacheDataSourceImpl *dataSource = [[DBCacheDataSourceImpl alloc] init];
dataSource.pmaximumElementInMemory = 20;
dataSource.pmaximumMemoryAllocated = 2;
dataSource.ppathForDiskCaching = [self applicationDocumentsDirectory];
//initialising CachingManager
id <CacheProtocol> cachingManager = [StockPile getInMemoryDiskCopyCacheUsingData:dataSource];
//using cachingManager to cache a string value
[cachingManager cacheValue:@"value" forKey:@"key"];
//using cachingManager to get a cached value
Value* data = [_cachingManager getValueForKey:@"key"];
我们将很喜欢贡献,请通过问题跟踪器报告错误,创建拉取请求(在 develop
分支上)并建议新的伟大功能(也在问题跟踪器中)。
StockPile 在 MIT 许可证下可用,因此您可以在商业和非商业项目中自由使用它。
Mudit Krishna Mathur [email protected]
Prabodh Prakash [邮箱地址保护,请替换显示为有效邮箱]