PINDiskCache.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. // PINCache is a modified version of TMCache
  2. // Modifications by Garrett Moon
  3. // Copyright (c) 2015 Pinterest. All rights reserved.
  4. #import <Foundation/Foundation.h>
  5. #import "Nullability.h"
  6. NS_ASSUME_NONNULL_BEGIN
  7. @class PINDiskCache;
  8. /**
  9. A callback block which provides only the cache as an argument
  10. */
  11. typedef void (^PINDiskCacheBlock)(PINDiskCache *cache);
  12. /**
  13. A callback block which provides the cache, key and object as arguments
  14. */
  15. typedef void (^PINDiskCacheObjectBlock)(PINDiskCache *cache, NSString *key, id <NSCoding> __nullable object, NSURL * __nullable fileURL);
  16. /**
  17. `PINDiskCache` is a thread safe key/value store backed by the file system. It accepts any object conforming
  18. to the `NSCoding` protocol, which includes the basic Foundation data types and collection classes and also
  19. many UIKit classes, notably `UIImage`. All work is performed on a serial queue shared by all instances in
  20. the app, and archiving is handled by `NSKeyedArchiver`. This is a particular advantage for `UIImage` because
  21. it skips `UIImagePNGRepresentation()` and retains information like scale and orientation.
  22. The designated initializer for `PINDiskCache` is <initWithName:>. The <name> string is used to create a directory
  23. under Library/Caches that scopes disk access for this instance. Multiple instances with the same name are *not*
  24. allowed as they would conflict with each other.
  25. Unless otherwise noted, all properties and methods are safe to access from any thread at any time. All blocks
  26. will cause the queue to wait, making it safe to access and manipulate the actual cache files on disk for the
  27. duration of the block.
  28. Because this cache is bound by disk I/O it can be much slower than <PINMemoryCache>, although values stored in
  29. `PINDiskCache` persist after application relaunch. Using <PINCache> is recommended over using `PINDiskCache`
  30. by itself, as it adds a fast layer of additional memory caching while still writing to disk.
  31. All access to the cache is dated so the that the least-used objects can be trimmed first. Setting an optional
  32. <ageLimit> will trigger a GCD timer to periodically to trim the cache with <trimToDate:>.
  33. */
  34. @interface PINDiskCache : NSObject
  35. #pragma mark -
  36. /// @name Core
  37. /**
  38. The name of this cache, used to create a directory under Library/Caches and also appearing in stack traces.
  39. */
  40. @property (readonly) NSString *name;
  41. /**
  42. The URL of the directory used by this cache, usually `Library/Caches/com.pinterest.PINDiskCache.(name)`
  43. @warning Do not interact with files under this URL except in <lockFileAccessWhileExecutingBlock:> or
  44. <synchronouslyLockFileAccessWhileExecutingBlock:>.
  45. */
  46. @property (readonly) NSURL *cacheURL;
  47. /**
  48. The total number of bytes used on disk, as reported by `NSURLTotalFileAllocatedSizeKey`.
  49. @warning This property should only be read from a call to <synchronouslyLockFileAccessWhileExecutingBlock:> or
  50. its asynchronous equivolent <lockFileAccessWhileExecutingBlock:>
  51. For example:
  52. // some background thread
  53. __block NSUInteger byteCount = 0;
  54. [_diskCache synchronouslyLockFileAccessWhileExecutingBlock:^(PINDiskCache *diskCache) {
  55. byteCount = diskCache.byteCount;
  56. }];
  57. */
  58. @property (readonly) NSUInteger byteCount;
  59. /**
  60. The maximum number of bytes allowed on disk. This value is checked every time an object is set, if the written
  61. size exceeds the limit a trim call is queued. Defaults to `0.0`, meaning no practical limit.
  62. */
  63. @property (assign) NSUInteger byteLimit;
  64. /**
  65. The maximum number of seconds an object is allowed to exist in the cache. Setting this to a value
  66. greater than `0.0` will start a recurring GCD timer with the same period that calls <trimToDate:>.
  67. Setting it back to `0.0` will stop the timer. Defaults to `0.0`, meaning no limit.
  68. */
  69. @property (assign) NSTimeInterval ageLimit;
  70. #pragma mark -
  71. /// @name Event Blocks
  72. /**
  73. A block to be executed just before an object is added to the cache. The queue waits during execution.
  74. */
  75. @property (copy) PINDiskCacheObjectBlock __nullable willAddObjectBlock;
  76. /**
  77. A block to be executed just before an object is removed from the cache. The queue waits during execution.
  78. */
  79. @property (copy) PINDiskCacheObjectBlock __nullable willRemoveObjectBlock;
  80. /**
  81. A block to be executed just before all objects are removed from the cache as a result of <removeAllObjects:>.
  82. The queue waits during execution.
  83. */
  84. @property (copy) PINDiskCacheBlock __nullable willRemoveAllObjectsBlock;
  85. /**
  86. A block to be executed just after an object is added to the cache. The queue waits during execution.
  87. */
  88. @property (copy) PINDiskCacheObjectBlock __nullable didAddObjectBlock;
  89. /**
  90. A block to be executed just after an object is removed from the cache. The queue waits during execution.
  91. */
  92. @property (copy) PINDiskCacheObjectBlock __nullable didRemoveObjectBlock;
  93. /**
  94. A block to be executed just after all objects are removed from the cache as a result of <removeAllObjects:>.
  95. The queue waits during execution.
  96. */
  97. @property (copy) PINDiskCacheBlock __nullable didRemoveAllObjectsBlock;
  98. #pragma mark -
  99. /// @name Initialization
  100. /**
  101. A shared cache.
  102. @result The shared singleton cache instance.
  103. */
  104. + (instancetype)sharedCache;
  105. /**
  106. Empties the trash with `DISPATCH_QUEUE_PRIORITY_BACKGROUND`. Does not use lock.
  107. */
  108. + (void)emptyTrash;
  109. - (instancetype)init NS_UNAVAILABLE;
  110. /**
  111. Multiple instances with the same name are allowed and can safely access
  112. the same data on disk thanks to the magic of seriality.
  113. @see name
  114. @param name The name of the cache.
  115. @result A new cache with the specified name.
  116. */
  117. - (instancetype)initWithName:(NSString *)name;
  118. /**
  119. The designated initializer. Multiple instances with the same name are allowed and can safely access
  120. the same data on disk thanks to the magic of seriality.
  121. @see name
  122. @param name The name of the cache.
  123. @param rootPath The path of the cache.
  124. @result A new cache with the specified name.
  125. */
  126. - (instancetype)initWithName:(NSString *)name rootPath:(NSString *)rootPath NS_DESIGNATED_INITIALIZER;
  127. #pragma mark -
  128. /// @name Asynchronous Methods
  129. /**
  130. Locks access to ivars and allows safe interaction with files on disk. This method returns immediately.
  131. @warning Calling synchronous methods on the diskCache inside this block will likely cause a deadlock.
  132. @param block A block to be executed when a lock is available.
  133. */
  134. - (void)lockFileAccessWhileExecutingBlock:(nullable PINDiskCacheBlock)block;
  135. /**
  136. Retrieves the object for the specified key. This method returns immediately and executes the passed
  137. block as soon as the object is available.
  138. @warning The fileURL is only valid for the duration of this block, do not use it after the block ends.
  139. @param key The key associated with the requested object.
  140. @param block A block to be executed serially when the object is available.
  141. */
  142. - (void)objectForKey:(NSString *)key block:(nullable PINDiskCacheObjectBlock)block;
  143. /**
  144. Retrieves the fileURL for the specified key without actually reading the data from disk. This method
  145. returns immediately and executes the passed block as soon as the object is available.
  146. @warning Access is protected for the duration of the block, but to maintain safe disk access do not
  147. access this fileURL after the block has ended.
  148. @param key The key associated with the requested object.
  149. @param block A block to be executed serially when the file URL is available.
  150. */
  151. - (void)fileURLForKey:(nullable NSString *)key block:(nullable PINDiskCacheObjectBlock)block;
  152. /**
  153. Stores an object in the cache for the specified key. This method returns immediately and executes the
  154. passed block as soon as the object has been stored.
  155. @param object An object to store in the cache.
  156. @param key A key to associate with the object. This string will be copied.
  157. @param block A block to be executed serially after the object has been stored, or nil.
  158. */
  159. - (void)setObject:(id <NSCoding>)object forKey:(NSString *)key block:(nullable PINDiskCacheObjectBlock)block;
  160. /**
  161. Removes the object for the specified key. This method returns immediately and executes the passed block
  162. as soon as the object has been removed.
  163. @param key The key associated with the object to be removed.
  164. @param block A block to be executed serially after the object has been removed, or nil.
  165. */
  166. - (void)removeObjectForKey:(NSString *)key block:(nullable PINDiskCacheObjectBlock)block;
  167. /**
  168. Removes all objects from the cache that have not been used since the specified date.
  169. This method returns immediately and executes the passed block as soon as the cache has been trimmed.
  170. @param date Objects that haven't been accessed since this date are removed from the cache.
  171. @param block A block to be executed serially after the cache has been trimmed, or nil.
  172. */
  173. - (void)trimToDate:(NSDate *)date block:(nullable PINDiskCacheBlock)block;
  174. /**
  175. Removes objects from the cache, largest first, until the cache is equal to or smaller than the specified byteCount.
  176. This method returns immediately and executes the passed block as soon as the cache has been trimmed.
  177. @param byteCount The cache will be trimmed equal to or smaller than this size.
  178. @param block A block to be executed serially after the cache has been trimmed, or nil.
  179. */
  180. - (void)trimToSize:(NSUInteger)byteCount block:(nullable PINDiskCacheBlock)block;
  181. /**
  182. Removes objects from the cache, ordered by date (least recently used first), until the cache is equal to or smaller
  183. than the specified byteCount. This method returns immediately and executes the passed block as soon as the cache has
  184. been trimmed.
  185. @param byteCount The cache will be trimmed equal to or smaller than this size.
  186. @param block A block to be executed serially after the cache has been trimmed, or nil.
  187. */
  188. - (void)trimToSizeByDate:(NSUInteger)byteCount block:(nullable PINDiskCacheBlock)block;
  189. /**
  190. Removes all objects from the cache. This method returns immediately and executes the passed block as soon as the
  191. cache has been cleared.
  192. @param block A block to be executed serially after the cache has been cleared, or nil.
  193. */
  194. - (void)removeAllObjects:(nullable PINDiskCacheBlock)block;
  195. /**
  196. Loops through all objects in the cache (reads and writes are suspended during the enumeration). Data is not actually
  197. read from disk, the `object` parameter of the block will be `nil` but the `fileURL` will be available.
  198. This method returns immediately.
  199. @param block A block to be executed for every object in the cache.
  200. @param completionBlock An optional block to be executed after the enumeration is complete.
  201. */
  202. - (void)enumerateObjectsWithBlock:(PINDiskCacheObjectBlock)block completionBlock:(nullable PINDiskCacheBlock)completionBlock;
  203. #pragma mark -
  204. /// @name Synchronous Methods
  205. /**
  206. Locks access to ivars and allows safe interaction with files on disk. This method only returns once the block
  207. has been run.
  208. @warning Calling synchronous methods on the diskCache inside this block will likely cause a deadlock.
  209. @param block A block to be executed when a lock is available.
  210. */
  211. - (void)synchronouslyLockFileAccessWhileExecutingBlock:(nullable PINDiskCacheBlock)block;
  212. /**
  213. Retrieves the object for the specified key. This method blocks the calling thread until the
  214. object is available.
  215. @see objectForKey:block:
  216. @param key The key associated with the object.
  217. @result The object for the specified key.
  218. */
  219. - (__nullable id <NSCoding>)objectForKey:(NSString *)key;
  220. /**
  221. Retrieves the file URL for the specified key. This method blocks the calling thread until the
  222. url is available. Do not use this URL anywhere except with <lockFileAccessWhileExecutingBlock:>. This method probably
  223. shouldn't even exist, just use the asynchronous one.
  224. @see fileURLForKey:block:
  225. @param key The key associated with the object.
  226. @result The file URL for the specified key.
  227. */
  228. - (NSURL *)fileURLForKey:(nullable NSString *)key;
  229. /**
  230. Stores an object in the cache for the specified key. This method blocks the calling thread until
  231. the object has been stored.
  232. @see setObject:forKey:block:
  233. @param object An object to store in the cache.
  234. @param key A key to associate with the object. This string will be copied.
  235. */
  236. - (void)setObject:(id <NSCoding>)object forKey:(NSString *)key;
  237. /**
  238. Removes the object for the specified key. This method blocks the calling thread until the object
  239. has been removed.
  240. @param key The key associated with the object to be removed.
  241. */
  242. - (void)removeObjectForKey:(NSString *)key;
  243. /**
  244. Removes all objects from the cache that have not been used since the specified date.
  245. This method blocks the calling thread until the cache has been trimmed.
  246. @param date Objects that haven't been accessed since this date are removed from the cache.
  247. */
  248. - (void)trimToDate:(nullable NSDate *)date;
  249. /**
  250. Removes objects from the cache, largest first, until the cache is equal to or smaller than the
  251. specified byteCount. This method blocks the calling thread until the cache has been trimmed.
  252. @param byteCount The cache will be trimmed equal to or smaller than this size.
  253. */
  254. - (void)trimToSize:(NSUInteger)byteCount;
  255. /**
  256. Removes objects from the cache, ordered by date (least recently used first), until the cache is equal to or
  257. smaller than the specified byteCount. This method blocks the calling thread until the cache has been trimmed.
  258. @param byteCount The cache will be trimmed equal to or smaller than this size.
  259. */
  260. - (void)trimToSizeByDate:(NSUInteger)byteCount;
  261. /**
  262. Removes all objects from the cache. This method blocks the calling thread until the cache has been cleared.
  263. */
  264. - (void)removeAllObjects;
  265. /**
  266. Loops through all objects in the cache (reads and writes are suspended during the enumeration). Data is not actually
  267. read from disk, the `object` parameter of the block will be `nil` but the `fileURL` will be available.
  268. This method blocks the calling thread until all objects have been enumerated.
  269. @param block A block to be executed for every object in the cache.
  270. @warning Do not call this method within the event blocks (<didRemoveObjectBlock>, etc.)
  271. Instead use the asynchronous version, <enumerateObjectsWithBlock:completionBlock:>.
  272. */
  273. - (void)enumerateObjectsWithBlock:(nullable PINDiskCacheObjectBlock)block;
  274. @end
  275. NS_ASSUME_NONNULL_END