YYDiskCache.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. //
  2. // YYDiskCache.h
  3. // YYKit <https://github.com/ibireme/YYKit>
  4. //
  5. // Created by ibireme on 15/2/11.
  6. // Copyright (c) 2015 ibireme.
  7. //
  8. // This source code is licensed under the MIT-style license found in the
  9. // LICENSE file in the root directory of this source tree.
  10. //
  11. #import <Foundation/Foundation.h>
  12. NS_ASSUME_NONNULL_BEGIN
  13. /**
  14. YYDiskCache is a thread-safe cache that stores key-value pairs backed by SQLite
  15. and file system (similar to NSURLCache's disk cache).
  16. YYDiskCache has these features:
  17. * It use LRU (least-recently-used) to remove objects.
  18. * It can be controlled by cost, count, and age.
  19. * It can be configured to automatically evict objects when there's no free disk space.
  20. * It can automatically decide the storage type (sqlite/file) for each object to get
  21. better performance.
  22. You may compile the latest version of sqlite and ignore the libsqlite3.dylib in
  23. iOS system to get 2x~4x speed up.
  24. */
  25. @interface YYDiskCache : NSObject
  26. #pragma mark - Attribute
  27. ///=============================================================================
  28. /// @name Attribute
  29. ///=============================================================================
  30. /** The name of the cache. Default is nil. */
  31. @property (nullable, copy) NSString *name;
  32. /** The path of the cache (read-only). */
  33. @property (readonly) NSString *path;
  34. /**
  35. If the object's data size (in bytes) is larger than this value, then object will
  36. be stored as a file, otherwise the object will be stored in sqlite.
  37. 0 means all objects will be stored as separated files, NSUIntegerMax means all
  38. objects will be stored in sqlite.
  39. The default value is 20480 (20KB).
  40. */
  41. @property (readonly) NSUInteger inlineThreshold;
  42. /**
  43. If this block is not nil, then the block will be used to archive object instead
  44. of NSKeyedArchiver. You can use this block to support the objects which do not
  45. conform to the `NSCoding` protocol.
  46. The default value is nil.
  47. */
  48. @property (nullable, copy) NSData *(^customArchiveBlock)(id object);
  49. /**
  50. If this block is not nil, then the block will be used to unarchive object instead
  51. of NSKeyedUnarchiver. You can use this block to support the objects which do not
  52. conform to the `NSCoding` protocol.
  53. The default value is nil.
  54. */
  55. @property (nullable, copy) id (^customUnarchiveBlock)(NSData *data);
  56. /**
  57. When an object needs to be saved as a file, this block will be invoked to generate
  58. a file name for a specified key. If the block is nil, the cache use md5(key) as
  59. default file name.
  60. The default value is nil.
  61. */
  62. @property (nullable, copy) NSString *(^customFileNameBlock)(NSString *key);
  63. #pragma mark - Limit
  64. ///=============================================================================
  65. /// @name Limit
  66. ///=============================================================================
  67. /**
  68. The maximum number of objects the cache should hold.
  69. @discussion The default value is NSUIntegerMax, which means no limit.
  70. This is not a strict limit — if the cache goes over the limit, some objects in the
  71. cache could be evicted later in background queue.
  72. */
  73. @property NSUInteger countLimit;
  74. /**
  75. The maximum total cost that the cache can hold before it starts evicting objects.
  76. @discussion The default value is NSUIntegerMax, which means no limit.
  77. This is not a strict limit — if the cache goes over the limit, some objects in the
  78. cache could be evicted later in background queue.
  79. */
  80. @property NSUInteger costLimit;
  81. /**
  82. The maximum expiry time of objects in cache.
  83. @discussion The default value is DBL_MAX, which means no limit.
  84. This is not a strict limit — if an object goes over the limit, the objects could
  85. be evicted later in background queue.
  86. */
  87. @property NSTimeInterval ageLimit;
  88. /**
  89. The minimum free disk space (in bytes) which the cache should kept.
  90. @discussion The default value is 0, which means no limit.
  91. If the free disk space is lower than this value, the cache will remove objects
  92. to free some disk space. This is not a strict limit—if the free disk space goes
  93. over the limit, the objects could be evicted later in background queue.
  94. */
  95. @property NSUInteger freeDiskSpaceLimit;
  96. /**
  97. The auto trim check time interval in seconds. Default is 60 (1 minute).
  98. @discussion The cache holds an internal timer to check whether the cache reaches
  99. its limits, and if the limit is reached, it begins to evict objects.
  100. */
  101. @property NSTimeInterval autoTrimInterval;
  102. /**
  103. Set `YES` to enable error logs for debug.
  104. */
  105. @property BOOL errorLogsEnabled;
  106. #pragma mark - Initializer
  107. ///=============================================================================
  108. /// @name Initializer
  109. ///=============================================================================
  110. - (instancetype)init UNAVAILABLE_ATTRIBUTE;
  111. + (instancetype)new UNAVAILABLE_ATTRIBUTE;
  112. /**
  113. Create a new cache based on the specified path.
  114. @param path Full path of a directory in which the cache will write data.
  115. Once initialized you should not read and write to this directory.
  116. @return A new cache object, or nil if an error occurs.
  117. @warning If the cache instance for the specified path already exists in memory,
  118. this method will return it directly, instead of creating a new instance.
  119. */
  120. - (nullable instancetype)initWithPath:(NSString *)path;
  121. /**
  122. The designated initializer.
  123. @param path Full path of a directory in which the cache will write data.
  124. Once initialized you should not read and write to this directory.
  125. @param threshold The data store inline threshold in bytes. If the object's data
  126. size (in bytes) is larger than this value, then object will be stored as a
  127. file, otherwise the object will be stored in sqlite. 0 means all objects will
  128. be stored as separated files, NSUIntegerMax means all objects will be stored
  129. in sqlite. If you don't know your object's size, 20480 is a good choice.
  130. After first initialized you should not change this value of the specified path.
  131. @return A new cache object, or nil if an error occurs.
  132. @warning If the cache instance for the specified path already exists in memory,
  133. this method will return it directly, instead of creating a new instance.
  134. */
  135. - (nullable instancetype)initWithPath:(NSString *)path
  136. inlineThreshold:(NSUInteger)threshold NS_DESIGNATED_INITIALIZER;
  137. #pragma mark - Access Methods
  138. ///=============================================================================
  139. /// @name Access Methods
  140. ///=============================================================================
  141. /**
  142. Returns a boolean value that indicates whether a given key is in cache.
  143. This method may blocks the calling thread until file read finished.
  144. @param key A string identifying the value. If nil, just return NO.
  145. @return Whether the key is in cache.
  146. */
  147. - (BOOL)containsObjectForKey:(NSString *)key;
  148. /**
  149. Returns a boolean value with the block that indicates whether a given key is in cache.
  150. This method returns immediately and invoke the passed block in background queue
  151. when the operation finished.
  152. @param key A string identifying the value. If nil, just return NO.
  153. @param block A block which will be invoked in background queue when finished.
  154. */
  155. - (void)containsObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key, BOOL contains))block;
  156. /**
  157. Returns the value associated with a given key.
  158. This method may blocks the calling thread until file read finished.
  159. @param key A string identifying the value. If nil, just return nil.
  160. @return The value associated with key, or nil if no value is associated with key.
  161. */
  162. - (nullable id<NSCoding>)objectForKey:(NSString *)key;
  163. /**
  164. Returns the value associated with a given key.
  165. This method returns immediately and invoke the passed block in background queue
  166. when the operation finished.
  167. @param key A string identifying the value. If nil, just return nil.
  168. @param block A block which will be invoked in background queue when finished.
  169. */
  170. - (void)objectForKey:(NSString *)key withBlock:(void(^)(NSString *key, id<NSCoding> _Nullable object))block;
  171. /**
  172. Sets the value of the specified key in the cache.
  173. This method may blocks the calling thread until file write finished.
  174. @param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`.
  175. @param key The key with which to associate the value. If nil, this method has no effect.
  176. */
  177. - (void)setObject:(nullable id<NSCoding>)object forKey:(NSString *)key;
  178. /**
  179. Sets the value of the specified key in the cache.
  180. This method returns immediately and invoke the passed block in background queue
  181. when the operation finished.
  182. @param object The object to be stored in the cache. If nil, it calls `removeObjectForKey:`.
  183. @param block A block which will be invoked in background queue when finished.
  184. */
  185. - (void)setObject:(nullable id<NSCoding>)object forKey:(NSString *)key withBlock:(void(^)(void))block;
  186. /**
  187. Removes the value of the specified key in the cache.
  188. This method may blocks the calling thread until file delete finished.
  189. @param key The key identifying the value to be removed. If nil, this method has no effect.
  190. */
  191. - (void)removeObjectForKey:(NSString *)key;
  192. /**
  193. Removes the value of the specified key in the cache.
  194. This method returns immediately and invoke the passed block in background queue
  195. when the operation finished.
  196. @param key The key identifying the value to be removed. If nil, this method has no effect.
  197. @param block A block which will be invoked in background queue when finished.
  198. */
  199. - (void)removeObjectForKey:(NSString *)key withBlock:(void(^)(NSString *key))block;
  200. /**
  201. Empties the cache.
  202. This method may blocks the calling thread until file delete finished.
  203. */
  204. - (void)removeAllObjects;
  205. /**
  206. Empties the cache.
  207. This method returns immediately and invoke the passed block in background queue
  208. when the operation finished.
  209. @param block A block which will be invoked in background queue when finished.
  210. */
  211. - (void)removeAllObjectsWithBlock:(void(^)(void))block;
  212. /**
  213. Empties the cache with block.
  214. This method returns immediately and executes the clear operation with block in background.
  215. @warning You should not send message to this instance in these blocks.
  216. @param progress This block will be invoked during removing, pass nil to ignore.
  217. @param end This block will be invoked at the end, pass nil to ignore.
  218. */
  219. - (void)removeAllObjectsWithProgressBlock:(nullable void(^)(int removedCount, int totalCount))progress
  220. endBlock:(nullable void(^)(BOOL error))end;
  221. /**
  222. Returns the number of objects in this cache.
  223. This method may blocks the calling thread until file read finished.
  224. @return The total objects count.
  225. */
  226. - (NSInteger)totalCount;
  227. /**
  228. Get the number of objects in this cache.
  229. This method returns immediately and invoke the passed block in background queue
  230. when the operation finished.
  231. @param block A block which will be invoked in background queue when finished.
  232. */
  233. - (void)totalCountWithBlock:(void(^)(NSInteger totalCount))block;
  234. /**
  235. Returns the total cost (in bytes) of objects in this cache.
  236. This method may blocks the calling thread until file read finished.
  237. @return The total objects cost in bytes.
  238. */
  239. - (NSInteger)totalCost;
  240. /**
  241. Get the total cost (in bytes) of objects in this cache.
  242. This method returns immediately and invoke the passed block in background queue
  243. when the operation finished.
  244. @param block A block which will be invoked in background queue when finished.
  245. */
  246. - (void)totalCostWithBlock:(void(^)(NSInteger totalCost))block;
  247. #pragma mark - Trim
  248. ///=============================================================================
  249. /// @name Trim
  250. ///=============================================================================
  251. /**
  252. Removes objects from the cache use LRU, until the `totalCount` is below the specified value.
  253. This method may blocks the calling thread until operation finished.
  254. @param count The total count allowed to remain after the cache has been trimmed.
  255. */
  256. - (void)trimToCount:(NSUInteger)count;
  257. /**
  258. Removes objects from the cache use LRU, until the `totalCount` is below the specified value.
  259. This method returns immediately and invoke the passed block in background queue
  260. when the operation finished.
  261. @param count The total count allowed to remain after the cache has been trimmed.
  262. @param block A block which will be invoked in background queue when finished.
  263. */
  264. - (void)trimToCount:(NSUInteger)count withBlock:(void(^)(void))block;
  265. /**
  266. Removes objects from the cache use LRU, until the `totalCost` is below the specified value.
  267. This method may blocks the calling thread until operation finished.
  268. @param cost The total cost allowed to remain after the cache has been trimmed.
  269. */
  270. - (void)trimToCost:(NSUInteger)cost;
  271. /**
  272. Removes objects from the cache use LRU, until the `totalCost` is below the specified value.
  273. This method returns immediately and invoke the passed block in background queue
  274. when the operation finished.
  275. @param cost The total cost allowed to remain after the cache has been trimmed.
  276. @param block A block which will be invoked in background queue when finished.
  277. */
  278. - (void)trimToCost:(NSUInteger)cost withBlock:(void(^)(void))block;
  279. /**
  280. Removes objects from the cache use LRU, until all expiry objects removed by the specified value.
  281. This method may blocks the calling thread until operation finished.
  282. @param age The maximum age of the object.
  283. */
  284. - (void)trimToAge:(NSTimeInterval)age;
  285. /**
  286. Removes objects from the cache use LRU, until all expiry objects removed by the specified value.
  287. This method returns immediately and invoke the passed block in background queue
  288. when the operation finished.
  289. @param age The maximum age of the object.
  290. @param block A block which will be invoked in background queue when finished.
  291. */
  292. - (void)trimToAge:(NSTimeInterval)age withBlock:(void(^)(void))block;
  293. #pragma mark - Extended Data
  294. ///=============================================================================
  295. /// @name Extended Data
  296. ///=============================================================================
  297. /**
  298. Get extended data from an object.
  299. @discussion See 'setExtendedData:toObject:' for more information.
  300. @param object An object.
  301. @return The extended data.
  302. */
  303. + (nullable NSData *)getExtendedDataFromObject:(id)object;
  304. /**
  305. Set extended data to an object.
  306. @discussion You can set any extended data to an object before you save the object
  307. to disk cache. The extended data will also be saved with this object. You can get
  308. the extended data later with "getExtendedDataFromObject:".
  309. @param extendedData The extended data (pass nil to remove).
  310. @param object The object.
  311. */
  312. + (void)setExtendedData:(nullable NSData *)extendedData toObject:(id)object;
  313. @end
  314. NS_ASSUME_NONNULL_END