PINDiskCache.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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 <PINCache/PINCacheMacros.h>
  6. #import <PINCache/PINCaching.h>
  7. #import <PINCache/PINCacheObjectSubscripting.h>
  8. NS_ASSUME_NONNULL_BEGIN
  9. @class PINDiskCache;
  10. @class PINOperationQueue;
  11. extern NSString * const PINDiskCachePrefix;
  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);
  16. /**
  17. A callback block which provides the key and fileURL of the object
  18. */
  19. typedef void (^PINDiskCacheFileURLBlock)(NSString *key, NSURL * _Nullable fileURL);
  20. /**
  21. A callback block which provides a BOOL value as argument
  22. */
  23. typedef void (^PINDiskCacheContainsBlock)(BOOL containsObject);
  24. /**
  25. * A block used to serialize object before writing to disk
  26. *
  27. * @param object Object to serialize
  28. * @param key The key associated with the object
  29. *
  30. * @return Serialized object representation
  31. */
  32. typedef NSData* _Nonnull(^PINDiskCacheSerializerBlock)(id<NSCoding> object, NSString *key);
  33. /**
  34. * A block used to deserialize objects
  35. *
  36. * @param data Serialized object data
  37. * @param key The key associated with the object
  38. *
  39. * @return Deserialized object
  40. */
  41. typedef id<NSCoding> _Nonnull(^PINDiskCacheDeserializerBlock)(NSData* data, NSString *key);
  42. /**
  43. `PINDiskCache` is a thread safe key/value store backed by the file system. It accepts any object conforming
  44. to the `NSCoding` protocol, which includes the basic Foundation data types and collection classes and also
  45. many UIKit classes, notably `UIImage`. All work is performed on a serial queue shared by all instances in
  46. the app, and archiving is handled by `NSKeyedArchiver`. This is a particular advantage for `UIImage` because
  47. it skips `UIImagePNGRepresentation()` and retains information like scale and orientation.
  48. The designated initializer for `PINDiskCache` is <initWithName:>. The <name> string is used to create a directory
  49. under Library/Caches that scopes disk access for this instance. Multiple instances with the same name are *not*
  50. allowed as they would conflict with each other.
  51. Unless otherwise noted, all properties and methods are safe to access from any thread at any time. All blocks
  52. will cause the queue to wait, making it safe to access and manipulate the actual cache files on disk for the
  53. duration of the block.
  54. Because this cache is bound by disk I/O it can be much slower than <PINMemoryCache>, although values stored in
  55. `PINDiskCache` persist after application relaunch. Using <PINCache> is recommended over using `PINDiskCache`
  56. by itself, as it adds a fast layer of additional memory caching while still writing to disk.
  57. All access to the cache is dated so the that the least-used objects can be trimmed first. Setting an optional
  58. <ageLimit> will trigger a GCD timer to periodically to trim the cache with <trimToDate:>.
  59. */
  60. PIN_SUBCLASSING_RESTRICTED
  61. @interface PINDiskCache : NSObject <PINCaching, PINCacheObjectSubscripting>
  62. #pragma mark - Class
  63. /**
  64. @param rootPath The path for where the cache should be stored.
  65. @param prefix The prefix for the cache name.
  66. @param name The name of the cache.
  67. @result The full URL of the cache.
  68. */
  69. + (NSURL *)cacheURLWithRootPath:(NSString *)rootPath prefix:(NSString *)prefix name:(NSString *)name;
  70. #pragma mark - Properties
  71. /// @name Core
  72. /**
  73. The prefix to the name of this cache, used to create a directory under Library/Caches and also appearing in stack traces.
  74. */
  75. @property (readonly) NSString *prefix;
  76. /**
  77. The URL of the directory used by this cache, usually `Library/Caches/com.pinterest.PINDiskCache.(name)`
  78. @warning Do not interact with files under this URL except in <lockFileAccessWhileExecutingBlock:> or
  79. <synchronouslyLockFileAccessWhileExecutingBlock:>.
  80. */
  81. @property (readonly) NSURL *cacheURL;
  82. /**
  83. The total number of bytes used on disk, as reported by `NSURLTotalFileAllocatedSizeKey`.
  84. @warning This property should only be read from a call to <synchronouslyLockFileAccessWhileExecutingBlock:> or
  85. its asynchronous equivalent <lockFileAccessWhileExecutingBlock:>
  86. For example:
  87. // some background thread
  88. __block NSUInteger byteCount = 0;
  89. [_diskCache synchronouslyLockFileAccessWhileExecutingBlock:^(PINDiskCache *diskCache) {
  90. byteCount = diskCache.byteCount;
  91. }];
  92. */
  93. @property (readonly) NSUInteger byteCount;
  94. /**
  95. The maximum number of bytes allowed on disk. This value is checked every time an object is set, if the written
  96. size exceeds the limit a trim call is queued. Defaults to `0.0`, meaning no practical limit.
  97. */
  98. @property (assign) NSUInteger byteLimit;
  99. /**
  100. The maximum number of seconds an object is allowed to exist in the cache. Setting this to a value
  101. greater than `0.0` will start a recurring GCD timer with the same period that calls <trimToDate:>.
  102. Setting it back to `0.0` will stop the timer. Defaults to `0.0`, meaning no limit.
  103. */
  104. @property (assign) NSTimeInterval ageLimit;
  105. /**
  106. Extension for all cache files on disk. Defaults to no extension.
  107. */
  108. @property (nullable, readonly) NSString * fileExtension;
  109. /**
  110. The writing protection option used when writing a file on disk. This value is used every time an object is set.
  111. NSDataWritingAtomic and NSDataWritingWithoutOverwriting are ignored if set
  112. Defaults to NSDataWritingFileProtectionNone.
  113. @warning Only new files are affected by the new writing protection. If you need all files to be affected,
  114. you'll have to purge and set the objects back to the cache
  115. Only available on iOS
  116. */
  117. #if TARGET_OS_IPHONE
  118. @property (assign) NSDataWritingOptions writingProtectionOption;
  119. #endif
  120. /**
  121. If ttlCache is YES, the cache behaves like a ttlCache. This means that once an object enters the
  122. cache, it only lives as long as self.ageLimit. This has the following implications:
  123. - Accessing an object in the cache does not extend that object's lifetime in the cache
  124. - When attempting to access an object in the cache that has lived longer than self.ageLimit,
  125. the cache will behave as if the object does not exist
  126. */
  127. @property (nonatomic, assign, getter=isTTLCache) BOOL ttlCache;
  128. #pragma mark - Event Blocks
  129. /// @name Event Blocks
  130. /**
  131. A block to be executed just before an object is added to the cache. The queue waits during execution.
  132. */
  133. @property (nullable, copy) PINDiskCacheObjectBlock willAddObjectBlock;
  134. /**
  135. A block to be executed just before an object is removed from the cache. The queue waits during execution.
  136. */
  137. @property (nullable, copy) PINDiskCacheObjectBlock willRemoveObjectBlock;
  138. /**
  139. A block to be executed just before all objects are removed from the cache as a result of <removeAllObjects:>.
  140. The queue waits during execution.
  141. */
  142. @property (nullable, copy) PINCacheBlock willRemoveAllObjectsBlock;
  143. /**
  144. A block to be executed just after an object is added to the cache. The queue waits during execution.
  145. */
  146. @property (nullable, copy) PINDiskCacheObjectBlock didAddObjectBlock;
  147. /**
  148. A block to be executed just after an object is removed from the cache. The queue waits during execution.
  149. */
  150. @property (nullable, copy) PINDiskCacheObjectBlock didRemoveObjectBlock;
  151. /**
  152. A block to be executed just after all objects are removed from the cache as a result of <removeAllObjects:>.
  153. The queue waits during execution.
  154. */
  155. @property (nullable, copy) PINCacheBlock didRemoveAllObjectsBlock;
  156. #pragma mark - Lifecycle
  157. /// @name Initialization
  158. /**
  159. A shared cache.
  160. @result The shared singleton cache instance.
  161. */
  162. @property (class, readonly, strong) PINDiskCache *sharedCache;
  163. /**
  164. Empties the trash with `DISPATCH_QUEUE_PRIORITY_BACKGROUND`. Does not use lock.
  165. */
  166. + (void)emptyTrash;
  167. - (instancetype)init NS_UNAVAILABLE;
  168. /**
  169. Multiple instances with the same name are allowed and can safely access
  170. the same data on disk thanks to the magic of seriality.
  171. @see name
  172. @param name The name of the cache.
  173. @result A new cache with the specified name.
  174. */
  175. - (instancetype)initWithName:(nonnull NSString *)name;
  176. /**
  177. Multiple instances with the same name are allowed and can safely access
  178. the same data on disk thanks to the magic of seriality.
  179. @see name
  180. @param name The name of the cache.
  181. @param fileExtension The file extension for files on disk.
  182. @result A new cache with the specified name.
  183. */
  184. - (instancetype)initWithName:(nonnull NSString *)name fileExtension:(nullable NSString *)fileExtension;
  185. /**
  186. Multiple instances with the same name are allowed and can safely access
  187. the same data on disk thanks to the magic of seriality.
  188. @see name
  189. @param name The name of the cache.
  190. @param rootPath The path of the cache.
  191. @param fileExtension The file extension for files on disk.
  192. @result A new cache with the specified name.
  193. */
  194. - (instancetype)initWithName:(nonnull NSString *)name rootPath:(nonnull NSString *)rootPath fileExtension:(nullable NSString *)fileExtension;
  195. /**
  196. @see name
  197. @param name The name of the cache.
  198. @param rootPath The path of the cache.
  199. @param serializer A block used to serialize object. If nil provided, default NSKeyedArchiver serialized will be used.
  200. @param deserializer A block used to deserialize object. If nil provided, default NSKeyedUnarchiver serialized will be used.
  201. @param fileExtension The file extension for files on disk.
  202. @result A new cache with the specified name.
  203. */
  204. - (instancetype)initWithName:(nonnull NSString *)name rootPath:(nonnull NSString *)rootPath serializer:(nullable PINDiskCacheSerializerBlock)serializer deserializer:(nullable PINDiskCacheDeserializerBlock)deserializer fileExtension:(nullable NSString *)fileExtension;
  205. /**
  206. The designated initializer allowing you to override default NSKeyedArchiver/NSKeyedUnarchiver serialization.
  207. @see name
  208. @param name The name of the cache.
  209. @param rootPath The path of the cache.
  210. @param serializer A block used to serialize object. If nil provided, default NSKeyedArchiver serialized will be used.
  211. @param deserializer A block used to deserialize object. If nil provided, default NSKeyedUnarchiver serialized will be used.
  212. @param fileExtension The file extension for files on disk.
  213. @param operationQueue A PINOperationQueue to run asynchronous operations
  214. @result A new cache with the specified name.
  215. */
  216. - (instancetype)initWithName:(nonnull NSString *)name rootPath:(nonnull NSString *)rootPath serializer:(nullable PINDiskCacheSerializerBlock)serializer deserializer:(nullable PINDiskCacheDeserializerBlock)deserializer fileExtension:(nullable NSString *)fileExtension operationQueue:(nonnull PINOperationQueue *)operationQueue __attribute__((deprecated));
  217. /**
  218. The designated initializer allowing you to override default NSKeyedArchiver/NSKeyedUnarchiver serialization.
  219. @see name
  220. @param name The name of the cache.
  221. @param prefix The prefix for the cache name. Defaults to com.pinterest.PINDiskCache
  222. @param rootPath The path of the cache.
  223. @param serializer A block used to serialize object. If nil provided, default NSKeyedArchiver serialized will be used.
  224. @param deserializer A block used to deserialize object. If nil provided, default NSKeyedUnarchiver serialized will be used.
  225. @param fileExtension The file extension for files on disk.
  226. @param operationQueue A PINOperationQueue to run asynchronous operations
  227. @result A new cache with the specified name.
  228. */
  229. - (instancetype)initWithName:(nonnull NSString *)name prefix:(nonnull NSString *)prefix rootPath:(nonnull NSString *)rootPath serializer:(nullable PINDiskCacheSerializerBlock)serializer deserializer:(nullable PINDiskCacheDeserializerBlock)deserializer fileExtension:(nullable NSString *)fileExtension operationQueue:(nonnull PINOperationQueue *)operationQueue NS_DESIGNATED_INITIALIZER;
  230. #pragma mark - Asynchronous Methods
  231. /// @name Asynchronous Methods
  232. /**
  233. Locks access to ivars and allows safe interaction with files on disk. This method returns immediately.
  234. @warning Calling synchronous methods on the diskCache inside this block will likely cause a deadlock.
  235. @param block A block to be executed when a lock is available.
  236. */
  237. - (void)lockFileAccessWhileExecutingBlockAsync:(PINCacheBlock)block;
  238. /**
  239. Retrieves the object for the specified key. This method returns immediately and executes the passed
  240. block as soon as the object is available.
  241. @param key The key associated with the requested object.
  242. @param block A block to be executed serially when the object is available.
  243. */
  244. - (void)objectForKeyAsync:(NSString *)key completion:(nullable PINDiskCacheObjectBlock)block;
  245. /**
  246. Retrieves the fileURL for the specified key without actually reading the data from disk. This method
  247. returns immediately and executes the passed block as soon as the object is available.
  248. @warning Access is protected for the duration of the block, but to maintain safe disk access do not
  249. access this fileURL after the block has ended.
  250. @warning The PINDiskCache lock is held while block is executed. Any synchronous calls to the diskcache
  251. or a cache which owns the instance of the disk cache are likely to cause a deadlock. This is why the block is
  252. *not* passed the instance of the disk cache. You should also avoid doing extensive work while this
  253. lock is held.
  254. @param key The key associated with the requested object.
  255. @param block A block to be executed serially when the file URL is available.
  256. */
  257. - (void)fileURLForKeyAsync:(NSString *)key completion:(PINDiskCacheFileURLBlock)block;
  258. /**
  259. Stores an object in the cache for the specified key. This method returns immediately and executes the
  260. passed block as soon as the object has been stored.
  261. @param object An object to store in the cache.
  262. @param key A key to associate with the object. This string will be copied.
  263. @param block A block to be executed serially after the object has been stored, or nil.
  264. */
  265. - (void)setObjectAsync:(id <NSCoding>)object forKey:(NSString *)key completion:(nullable PINDiskCacheObjectBlock)block;
  266. /**
  267. Stores an object in the cache for the specified key and the specified memory cost. If the cost causes the total
  268. to go over the <memoryCache.costLimit> the cache is trimmed (oldest objects first). This method returns immediately
  269. and executes the passed block after the object has been stored, potentially in parallel with other blocks
  270. on the <concurrentQueue>.
  271. @param object An object to store in the cache.
  272. @param key A key to associate with the object. This string will be copied.
  273. @param cost An amount to add to the <memoryCache.totalCost>.
  274. @param block A block to be executed concurrently after the object has been stored, or nil.
  275. */
  276. - (void)setObjectAsync:(id <NSCoding>)object forKey:(NSString *)key withCost:(NSUInteger)cost completion:(nullable PINCacheObjectBlock)block;
  277. /**
  278. Removes the object for the specified key. This method returns immediately and executes the passed block
  279. as soon as the object has been removed.
  280. @param key The key associated with the object to be removed.
  281. @param block A block to be executed serially after the object has been removed, or nil.
  282. */
  283. - (void)removeObjectForKeyAsync:(NSString *)key completion:(nullable PINDiskCacheObjectBlock)block;
  284. /**
  285. Removes objects from the cache, largest first, until the cache is equal to or smaller than the specified byteCount.
  286. This method returns immediately and executes the passed block as soon as the cache has been trimmed.
  287. @param byteCount The cache will be trimmed equal to or smaller than this size.
  288. @param block A block to be executed serially after the cache has been trimmed, or nil.
  289. */
  290. - (void)trimToSizeAsync:(NSUInteger)byteCount completion:(nullable PINCacheBlock)block;
  291. /**
  292. Removes objects from the cache, ordered by date (least recently used first), until the cache is equal to or smaller
  293. than the specified byteCount. This method returns immediately and executes the passed block as soon as the cache has
  294. been trimmed.
  295. @param byteCount The cache will be trimmed equal to or smaller than this size.
  296. @param block A block to be executed serially after the cache has been trimmed, or nil.
  297. */
  298. - (void)trimToSizeByDateAsync:(NSUInteger)byteCount completion:(nullable PINCacheBlock)block;
  299. /**
  300. Loops through all objects in the cache (reads and writes are suspended during the enumeration). Data is not actually
  301. read from disk, the `object` parameter of the block will be `nil` but the `fileURL` will be available.
  302. This method returns immediately.
  303. @param block A block to be executed for every object in the cache.
  304. @param completionBlock An optional block to be executed after the enumeration is complete.
  305. @warning The PINDiskCache lock is held while block is executed. Any synchronous calls to the diskcache
  306. or a cache which owns the instance of the disk cache are likely to cause a deadlock. This is why the block is
  307. *not* passed the instance of the disk cache. You should also avoid doing extensive work while this
  308. lock is held.
  309. */
  310. - (void)enumerateObjectsWithBlockAsync:(PINDiskCacheFileURLBlock)block completionBlock:(nullable PINCacheBlock)completionBlock;
  311. #pragma mark - Synchronous Methods
  312. /// @name Synchronous Methods
  313. /**
  314. Locks access to ivars and allows safe interaction with files on disk. This method only returns once the block
  315. has been run.
  316. @warning Calling synchronous methods on the diskCache inside this block will likely cause a deadlock.
  317. @param block A block to be executed when a lock is available.
  318. */
  319. - (void)synchronouslyLockFileAccessWhileExecutingBlock:(PIN_NOESCAPE PINCacheBlock)block;
  320. /**
  321. Retrieves the object for the specified key. This method blocks the calling thread until the
  322. object is available.
  323. @see objectForKeyAsync:completion:
  324. @param key The key associated with the object.
  325. @result The object for the specified key.
  326. */
  327. - (nullable id <NSCoding>)objectForKey:(NSString *)key;
  328. /**
  329. Retrieves the file URL for the specified key. This method blocks the calling thread until the
  330. url is available. Do not use this URL anywhere except with <lockFileAccessWhileExecutingBlock:>. This method probably
  331. shouldn't even exist, just use the asynchronous one.
  332. @see fileURLForKeyAsync:completion:
  333. @param key The key associated with the object.
  334. @result The file URL for the specified key.
  335. */
  336. - (nullable NSURL *)fileURLForKey:(nullable NSString *)key;
  337. /**
  338. Stores an object in the cache for the specified key. This method blocks the calling thread until
  339. the object has been stored.
  340. @see setObjectAsync:forKey:completion:
  341. @param object An object to store in the cache.
  342. @param key A key to associate with the object. This string will be copied.
  343. */
  344. - (void)setObject:(nullable id <NSCoding>)object forKey:(NSString *)key;
  345. /**
  346. Removes objects from the cache, largest first, until the cache is equal to or smaller than the
  347. specified byteCount. This method blocks the calling thread until the cache has been trimmed.
  348. @see trimToSizeAsync:
  349. @param byteCount The cache will be trimmed equal to or smaller than this size.
  350. */
  351. - (void)trimToSize:(NSUInteger)byteCount;
  352. /**
  353. Removes objects from the cache, ordered by date (least recently used first), until the cache is equal to or
  354. smaller than the specified byteCount. This method blocks the calling thread until the cache has been trimmed.
  355. @see trimToSizeByDateAsync:
  356. @param byteCount The cache will be trimmed equal to or smaller than this size.
  357. */
  358. - (void)trimToSizeByDate:(NSUInteger)byteCount;
  359. /**
  360. Loops through all objects in the cache (reads and writes are suspended during the enumeration). Data is not actually
  361. read from disk, the `object` parameter of the block will be `nil` but the `fileURL` will be available.
  362. This method blocks the calling thread until all objects have been enumerated.
  363. @see enumerateObjectsWithBlockAsync:completionBlock
  364. @param block A block to be executed for every object in the cache.
  365. @warning Do not call this method within the event blocks (<didRemoveObjectBlock>, etc.)
  366. Instead use the asynchronous version, <enumerateObjectsWithBlock:completionBlock:>.
  367. @warning The PINDiskCache lock is held while block is executed. Any synchronous calls to the diskcache
  368. or a cache which owns the instance of the disk cache are likely to cause a deadlock. This is why the block is
  369. *not* passed the instance of the disk cache. You should also avoid doing extensive work while this
  370. lock is held.
  371. */
  372. - (void)enumerateObjectsWithBlock:(PIN_NOESCAPE PINDiskCacheFileURLBlock)block;
  373. @end
  374. #pragma mark - Deprecated
  375. /**
  376. A callback block which provides only the cache as an argument
  377. */
  378. typedef void (^PINDiskCacheBlock)(PINDiskCache *cache);
  379. /**
  380. A callback block which provides the cache, key and object as arguments
  381. */
  382. typedef void (^PINDiskCacheObjectBlock)(PINDiskCache *cache, NSString *key, id <NSCoding> _Nullable object);
  383. @interface PINDiskCache (Deprecated)
  384. - (void)lockFileAccessWhileExecutingBlock:(nullable PINCacheBlock)block __attribute__((deprecated));
  385. - (void)containsObjectForKey:(NSString *)key block:(PINDiskCacheContainsBlock)block __attribute__((deprecated));
  386. - (void)objectForKey:(NSString *)key block:(nullable PINDiskCacheObjectBlock)block __attribute__((deprecated));
  387. - (void)fileURLForKey:(NSString *)key block:(nullable PINDiskCacheFileURLBlock)block __attribute__((deprecated));
  388. - (void)setObject:(id <NSCoding>)object forKey:(NSString *)key block:(nullable PINDiskCacheObjectBlock)block __attribute__((deprecated));
  389. - (void)removeObjectForKey:(NSString *)key block:(nullable PINDiskCacheObjectBlock)block __attribute__((deprecated));
  390. - (void)trimToDate:(NSDate *)date block:(nullable PINDiskCacheBlock)block __attribute__((deprecated));
  391. - (void)trimToSize:(NSUInteger)byteCount block:(nullable PINDiskCacheBlock)block __attribute__((deprecated));
  392. - (void)trimToSizeByDate:(NSUInteger)byteCount block:(nullable PINDiskCacheBlock)block __attribute__((deprecated));
  393. - (void)removeAllObjects:(nullable PINDiskCacheBlock)block __attribute__((deprecated));
  394. - (void)enumerateObjectsWithBlock:(PINDiskCacheFileURLBlock)block completionBlock:(nullable PINDiskCacheBlock)completionBlock __attribute__((deprecated));
  395. @end
  396. NS_ASSUME_NONNULL_END