PINDiskCache.m 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  1. // PINCache is a modified version of TMCache
  2. // Modifications by Garrett Moon
  3. // Copyright (c) 2015 Pinterest. All rights reserved.
  4. #import "PINDiskCache.h"
  5. #if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0
  6. #import <UIKit/UIKit.h>
  7. #endif
  8. #import <pthread.h>
  9. #import "PINOperationQueue.h"
  10. #define PINDiskCacheError(error) if (error) { NSLog(@"%@ (%d) ERROR: %@", \
  11. [[NSString stringWithUTF8String:__FILE__] lastPathComponent], \
  12. __LINE__, [error localizedDescription]); }
  13. static NSString * const PINDiskCachePrefix = @"com.pinterest.PINDiskCache";
  14. static NSString * const PINDiskCacheSharedName = @"PINDiskCacheShared";
  15. typedef NS_ENUM(NSUInteger, PINDiskCacheCondition) {
  16. PINDiskCacheConditionNotReady = 0,
  17. PINDiskCacheConditionReady = 1,
  18. };
  19. @interface PINDiskCache () {
  20. NSConditionLock *_instanceLock;
  21. PINDiskCacheSerializerBlock _serializer;
  22. PINDiskCacheDeserializerBlock _deserializer;
  23. }
  24. @property (assign) NSUInteger byteCount;
  25. @property (strong, nonatomic) NSURL *cacheURL;
  26. @property (strong, nonatomic) PINOperationQueue *operationQueue;
  27. @property (strong, nonatomic) NSMutableDictionary *dates;
  28. @property (strong, nonatomic) NSMutableDictionary *sizes;
  29. @end
  30. @implementation PINDiskCache
  31. @synthesize willAddObjectBlock = _willAddObjectBlock;
  32. @synthesize willRemoveObjectBlock = _willRemoveObjectBlock;
  33. @synthesize willRemoveAllObjectsBlock = _willRemoveAllObjectsBlock;
  34. @synthesize didAddObjectBlock = _didAddObjectBlock;
  35. @synthesize didRemoveObjectBlock = _didRemoveObjectBlock;
  36. @synthesize didRemoveAllObjectsBlock = _didRemoveAllObjectsBlock;
  37. @synthesize byteLimit = _byteLimit;
  38. @synthesize ageLimit = _ageLimit;
  39. @synthesize ttlCache = _ttlCache;
  40. #if TARGET_OS_IPHONE
  41. @synthesize writingProtectionOption = _writingProtectionOption;
  42. #endif
  43. #pragma mark - Initialization -
  44. - (instancetype)init
  45. {
  46. @throw [NSException exceptionWithName:@"Must initialize with a name" reason:@"PINDiskCache must be initialized with a name. Call initWithName: instead." userInfo:nil];
  47. return [self initWithName:@""];
  48. }
  49. - (instancetype)initWithName:(NSString *)name
  50. {
  51. return [self initWithName:name fileExtension:nil];
  52. }
  53. - (instancetype)initWithName:(NSString *)name fileExtension:(NSString *)fileExtension
  54. {
  55. return [self initWithName:name rootPath:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] fileExtension:fileExtension];
  56. }
  57. - (instancetype)initWithName:(NSString *)name rootPath:(NSString *)rootPath fileExtension:(NSString *)fileExtension
  58. {
  59. return [self initWithName:name rootPath:rootPath serializer:nil deserializer:nil fileExtension:fileExtension];
  60. }
  61. - (instancetype)initWithName:(NSString *)name rootPath:(NSString *)rootPath serializer:(PINDiskCacheSerializerBlock)serializer deserializer:(PINDiskCacheDeserializerBlock)deserializer fileExtension:(NSString *)fileExtension
  62. {
  63. return [self initWithName:name rootPath:rootPath serializer:serializer deserializer:deserializer fileExtension:fileExtension operationQueue:[PINOperationQueue sharedOperationQueue]];
  64. }
  65. - (instancetype)initWithName:(NSString *)name rootPath:(NSString *)rootPath serializer:(PINDiskCacheSerializerBlock)serializer deserializer:(PINDiskCacheDeserializerBlock)deserializer fileExtension:(NSString *)fileExtension operationQueue:(PINOperationQueue *)operationQueue
  66. {
  67. if (!name)
  68. return nil;
  69. if ((serializer && !deserializer) ||
  70. (!serializer && deserializer)){
  71. @throw [NSException exceptionWithName:@"Must initialize with a both serializer and deserializer" reason:@"PINDiskCache must be initialized with a serializer and deserializer." userInfo:nil];
  72. return nil;
  73. }
  74. if (self = [super init]) {
  75. _name = [name copy];
  76. _fileExtension = [fileExtension copy];
  77. _operationQueue = operationQueue;
  78. _instanceLock = [[NSConditionLock alloc] initWithCondition:PINDiskCacheConditionNotReady];
  79. _willAddObjectBlock = nil;
  80. _willRemoveObjectBlock = nil;
  81. _willRemoveAllObjectsBlock = nil;
  82. _didAddObjectBlock = nil;
  83. _didRemoveObjectBlock = nil;
  84. _didRemoveAllObjectsBlock = nil;
  85. _byteCount = 0;
  86. _byteLimit = 0;
  87. _ageLimit = 0.0;
  88. #if TARGET_OS_IPHONE
  89. _writingProtectionOption = NSDataWritingFileProtectionNone;
  90. #endif
  91. _dates = [[NSMutableDictionary alloc] init];
  92. _sizes = [[NSMutableDictionary alloc] init];
  93. NSString *pathComponent = [[NSString alloc] initWithFormat:@"%@.%@", PINDiskCachePrefix, _name];
  94. _cacheURL = [NSURL fileURLWithPathComponents:@[ rootPath, pathComponent ]];
  95. //setup serializers
  96. if(serializer) {
  97. _serializer = [serializer copy];
  98. } else {
  99. _serializer = self.defaultSerializer;
  100. }
  101. if(deserializer) {
  102. _deserializer = [deserializer copy];
  103. } else {
  104. _deserializer = self.defaultDeserializer;
  105. }
  106. //we don't want to do anything without setting up the disk cache, but we also don't want to block init, it can take a while to initialize. This must *not* be done on _operationQueue because other operations added may hold the lock and fill up the queue.
  107. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  108. //should always be able to aquire the lock unless the below code is running.
  109. [_instanceLock lockWhenCondition:PINDiskCacheConditionNotReady];
  110. [self _locked_createCacheDirectory];
  111. [self _locked_initializeDiskProperties];
  112. [_instanceLock unlockWithCondition:PINDiskCacheConditionReady];
  113. });
  114. }
  115. return self;
  116. }
  117. - (NSString *)description
  118. {
  119. return [[NSString alloc] initWithFormat:@"%@.%@.%p", PINDiskCachePrefix, _name, (void *)self];
  120. }
  121. + (instancetype)sharedCache
  122. {
  123. static id cache;
  124. static dispatch_once_t predicate;
  125. dispatch_once(&predicate, ^{
  126. cache = [[self alloc] initWithName:PINDiskCacheSharedName];
  127. });
  128. return cache;
  129. }
  130. #pragma mark - Private Methods -
  131. - (NSURL *)encodedFileURLForKey:(NSString *)key
  132. {
  133. if (![key length])
  134. return nil;
  135. //Significantly improve performance by indicating that the URL will *not* result in a directory.
  136. //Also note that accessing _cacheURL is safe without the lock because it is only set on init.
  137. return [_cacheURL URLByAppendingPathComponent:[self encodedString:key] isDirectory:NO];
  138. }
  139. - (NSString *)keyForEncodedFileURL:(NSURL *)url
  140. {
  141. NSString *fileName = [url lastPathComponent];
  142. if (!fileName)
  143. return nil;
  144. return [self decodedString:fileName];
  145. }
  146. - (NSString *)encodedString:(NSString *)string
  147. {
  148. if (![string length]) {
  149. return @"";
  150. }
  151. if ([string respondsToSelector:@selector(stringByAddingPercentEncodingWithAllowedCharacters:)]) {
  152. NSString *encodedString = [string stringByAddingPercentEncodingWithAllowedCharacters:[[NSCharacterSet characterSetWithCharactersInString:@".:/%"] invertedSet]];
  153. if (self.fileExtension.length > 0) {
  154. return [encodedString stringByAppendingPathExtension:self.fileExtension];
  155. }
  156. else {
  157. return encodedString;
  158. }
  159. }
  160. else {
  161. CFStringRef static const charsToEscape = CFSTR(".:/%");
  162. #pragma clang diagnostic push
  163. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  164. CFStringRef escapedString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
  165. (__bridge CFStringRef)string,
  166. NULL,
  167. charsToEscape,
  168. kCFStringEncodingUTF8);
  169. #pragma clang diagnostic pop
  170. if (self.fileExtension.length > 0) {
  171. return [(__bridge_transfer NSString *)escapedString stringByAppendingPathExtension:self.fileExtension];
  172. }
  173. else {
  174. return (__bridge_transfer NSString *)escapedString;
  175. }
  176. }
  177. }
  178. - (NSString *)decodedString:(NSString *)string
  179. {
  180. if (![string length]) {
  181. return @"";
  182. }
  183. if ([string respondsToSelector:@selector(stringByRemovingPercentEncoding)]) {
  184. return [string stringByRemovingPercentEncoding];
  185. }
  186. else {
  187. #pragma clang diagnostic push
  188. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  189. CFStringRef unescapedString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
  190. (__bridge CFStringRef)string,
  191. CFSTR(""),
  192. kCFStringEncodingUTF8);
  193. #pragma clang diagnostic pop
  194. return (__bridge_transfer NSString *)unescapedString;
  195. }
  196. }
  197. -(PINDiskCacheSerializerBlock) defaultSerializer
  198. {
  199. return ^NSData*(id<NSCoding> object, NSString *key){
  200. return [NSKeyedArchiver archivedDataWithRootObject:object];
  201. };
  202. }
  203. -(PINDiskCacheDeserializerBlock) defaultDeserializer
  204. {
  205. return ^id(NSData * data, NSString *key){
  206. return [NSKeyedUnarchiver unarchiveObjectWithData:data];
  207. };
  208. }
  209. #pragma mark - Private Trash Methods -
  210. + (dispatch_queue_t)sharedTrashQueue
  211. {
  212. static dispatch_queue_t trashQueue;
  213. static dispatch_once_t predicate;
  214. dispatch_once(&predicate, ^{
  215. NSString *queueName = [[NSString alloc] initWithFormat:@"%@.trash", PINDiskCachePrefix];
  216. trashQueue = dispatch_queue_create([queueName UTF8String], DISPATCH_QUEUE_SERIAL);
  217. dispatch_set_target_queue(trashQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0));
  218. });
  219. return trashQueue;
  220. }
  221. + (NSURL *)sharedTrashURL
  222. {
  223. static NSURL *sharedTrashURL;
  224. static dispatch_once_t predicate;
  225. dispatch_once(&predicate, ^{
  226. sharedTrashURL = [[[NSURL alloc] initFileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:PINDiskCachePrefix isDirectory:YES];
  227. if (![[NSFileManager defaultManager] fileExistsAtPath:[sharedTrashURL path]]) {
  228. NSError *error = nil;
  229. [[NSFileManager defaultManager] createDirectoryAtURL:sharedTrashURL
  230. withIntermediateDirectories:YES
  231. attributes:nil
  232. error:&error];
  233. PINDiskCacheError(error);
  234. }
  235. });
  236. return sharedTrashURL;
  237. }
  238. + (BOOL)moveItemAtURLToTrash:(NSURL *)itemURL
  239. {
  240. if (![[NSFileManager defaultManager] fileExistsAtPath:[itemURL path]])
  241. return NO;
  242. NSError *error = nil;
  243. NSString *uniqueString = [[NSProcessInfo processInfo] globallyUniqueString];
  244. NSURL *uniqueTrashURL = [[PINDiskCache sharedTrashURL] URLByAppendingPathComponent:uniqueString isDirectory:NO];
  245. BOOL moved = [[NSFileManager defaultManager] moveItemAtURL:itemURL toURL:uniqueTrashURL error:&error];
  246. PINDiskCacheError(error);
  247. return moved;
  248. }
  249. + (void)emptyTrash
  250. {
  251. dispatch_async([self sharedTrashQueue], ^{
  252. NSError *searchTrashedItemsError = nil;
  253. NSArray *trashedItems = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:[self sharedTrashURL]
  254. includingPropertiesForKeys:nil
  255. options:0
  256. error:&searchTrashedItemsError];
  257. PINDiskCacheError(searchTrashedItemsError);
  258. for (NSURL *trashedItemURL in trashedItems) {
  259. NSError *removeTrashedItemError = nil;
  260. [[NSFileManager defaultManager] removeItemAtURL:trashedItemURL error:&removeTrashedItemError];
  261. PINDiskCacheError(removeTrashedItemError);
  262. }
  263. });
  264. }
  265. #pragma mark - Private Queue Methods -
  266. - (BOOL)_locked_createCacheDirectory
  267. {
  268. if ([[NSFileManager defaultManager] fileExistsAtPath:[_cacheURL path]])
  269. return NO;
  270. NSError *error = nil;
  271. BOOL success = [[NSFileManager defaultManager] createDirectoryAtURL:_cacheURL
  272. withIntermediateDirectories:YES
  273. attributes:nil
  274. error:&error];
  275. PINDiskCacheError(error);
  276. return success;
  277. }
  278. - (void)_locked_initializeDiskProperties
  279. {
  280. NSUInteger byteCount = 0;
  281. NSArray *keys = @[ NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey ];
  282. NSError *error = nil;
  283. NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:_cacheURL
  284. includingPropertiesForKeys:keys
  285. options:NSDirectoryEnumerationSkipsHiddenFiles
  286. error:&error];
  287. PINDiskCacheError(error);
  288. for (NSURL *fileURL in files) {
  289. NSString *key = [self keyForEncodedFileURL:fileURL];
  290. error = nil;
  291. NSDictionary *dictionary = [fileURL resourceValuesForKeys:keys error:&error];
  292. PINDiskCacheError(error);
  293. NSDate *date = [dictionary objectForKey:NSURLContentModificationDateKey];
  294. if (date && key)
  295. [_dates setObject:date forKey:key];
  296. NSNumber *fileSize = [dictionary objectForKey:NSURLTotalFileAllocatedSizeKey];
  297. if (fileSize) {
  298. [_sizes setObject:fileSize forKey:key];
  299. byteCount += [fileSize unsignedIntegerValue];
  300. }
  301. }
  302. if (byteCount > 0)
  303. self.byteCount = byteCount; // atomic
  304. }
  305. - (void)asynchronouslySetFileModificationDate:(NSDate *)date forURL:(NSURL *)fileURL
  306. {
  307. __weak PINDiskCache *weakSelf = self;
  308. [self.operationQueue addOperation:^{
  309. PINDiskCache *strongSelf = weakSelf;
  310. if (strongSelf) {
  311. [strongSelf lock];
  312. [strongSelf _locked_setFileModificationDate:date forURL:fileURL];
  313. [strongSelf unlock];
  314. }
  315. } withPriority:PINOperationQueuePriorityLow];
  316. }
  317. - (BOOL)_locked_setFileModificationDate:(NSDate *)date forURL:(NSURL *)fileURL
  318. {
  319. if (!date || !fileURL) {
  320. return NO;
  321. }
  322. NSError *error = nil;
  323. BOOL success = [[NSFileManager defaultManager] setAttributes:@{ NSFileModificationDate: date }
  324. ofItemAtPath:[fileURL path]
  325. error:&error];
  326. PINDiskCacheError(error);
  327. if (success) {
  328. NSString *key = [self keyForEncodedFileURL:fileURL];
  329. if (key) {
  330. [_dates setObject:date forKey:key];
  331. }
  332. }
  333. return success;
  334. }
  335. - (BOOL)removeFileAndExecuteBlocksForKey:(NSString *)key
  336. {
  337. NSURL *fileURL = [self encodedFileURLForKey:key];
  338. [self lock];
  339. if (!fileURL || ![[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) {
  340. [self unlock];
  341. return NO;
  342. }
  343. PINDiskCacheObjectBlock willRemoveObjectBlock = _willRemoveObjectBlock;
  344. if (willRemoveObjectBlock) {
  345. [self unlock];
  346. willRemoveObjectBlock(self, key, nil);
  347. [self lock];
  348. }
  349. BOOL trashed = [PINDiskCache moveItemAtURLToTrash:fileURL];
  350. if (!trashed) {
  351. [self unlock];
  352. return NO;
  353. }
  354. [PINDiskCache emptyTrash];
  355. NSNumber *byteSize = [_sizes objectForKey:key];
  356. if (byteSize)
  357. self.byteCount = _byteCount - [byteSize unsignedIntegerValue]; // atomic
  358. [_sizes removeObjectForKey:key];
  359. [_dates removeObjectForKey:key];
  360. PINDiskCacheObjectBlock didRemoveObjectBlock = _didRemoveObjectBlock;
  361. if (didRemoveObjectBlock) {
  362. [self unlock];
  363. _didRemoveObjectBlock(self, key, nil);
  364. [self lock];
  365. }
  366. [self unlock];
  367. return YES;
  368. }
  369. - (void)trimDiskToSize:(NSUInteger)trimByteCount
  370. {
  371. [self lock];
  372. if (_byteCount > trimByteCount) {
  373. NSArray *keysSortedBySize = [_sizes keysSortedByValueUsingSelector:@selector(compare:)];
  374. for (NSString *key in [keysSortedBySize reverseObjectEnumerator]) { // largest objects first
  375. [self unlock];
  376. //unlock, removeFileAndExecuteBlocksForKey handles locking itself
  377. [self removeFileAndExecuteBlocksForKey:key];
  378. [self lock];
  379. if (_byteCount <= trimByteCount)
  380. break;
  381. }
  382. }
  383. [self unlock];
  384. }
  385. - (void)trimDiskToSizeByDate:(NSUInteger)trimByteCount
  386. {
  387. [self lock];
  388. if (_byteCount > trimByteCount) {
  389. NSArray *keysSortedByDate = [_dates keysSortedByValueUsingSelector:@selector(compare:)];
  390. for (NSString *key in keysSortedByDate) { // oldest objects first
  391. [self unlock];
  392. //unlock, removeFileAndExecuteBlocksForKey handles locking itself
  393. [self removeFileAndExecuteBlocksForKey:key];
  394. [self lock];
  395. if (_byteCount <= trimByteCount)
  396. break;
  397. }
  398. }
  399. [self unlock];
  400. }
  401. - (void)trimDiskToDate:(NSDate *)trimDate
  402. {
  403. [self lock];
  404. NSArray *keysSortedByDate = [_dates keysSortedByValueUsingSelector:@selector(compare:)];
  405. for (NSString *key in keysSortedByDate) { // oldest files first
  406. NSDate *accessDate = [_dates objectForKey:key];
  407. if (!accessDate)
  408. continue;
  409. if ([accessDate compare:trimDate] == NSOrderedAscending) { // older than trim date
  410. [self unlock];
  411. //unlock, removeFileAndExecuteBlocksForKey handles locking itself
  412. [self removeFileAndExecuteBlocksForKey:key];
  413. [self lock];
  414. } else {
  415. break;
  416. }
  417. }
  418. [self unlock];
  419. }
  420. - (void)trimToAgeLimitRecursively
  421. {
  422. [self lock];
  423. NSTimeInterval ageLimit = _ageLimit;
  424. [self unlock];
  425. if (ageLimit == 0.0)
  426. return;
  427. NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:-ageLimit];
  428. [self trimDiskToDate:date];
  429. __weak PINDiskCache *weakSelf = self;
  430. dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_ageLimit * NSEC_PER_SEC));
  431. dispatch_after(time, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
  432. PINDiskCache *strongSelf = weakSelf;
  433. [strongSelf.operationQueue addOperation:^{
  434. PINDiskCache *strongSelf = weakSelf;
  435. [strongSelf trimToAgeLimitRecursively];
  436. } withPriority:PINOperationQueuePriorityLow];
  437. });
  438. }
  439. #pragma mark - Public Asynchronous Methods -
  440. - (void)lockFileAccessWhileExecutingBlock:(void(^)(PINDiskCache *diskCache))block
  441. {
  442. __weak PINDiskCache *weakSelf = self;
  443. [self.operationQueue addOperation:^{
  444. PINDiskCache *strongSelf = weakSelf;
  445. if (block) {
  446. [strongSelf lock];
  447. block(strongSelf);
  448. [strongSelf unlock];
  449. }
  450. } withPriority:PINOperationQueuePriorityLow];
  451. }
  452. - (void)containsObjectForKey:(NSString *)key block:(PINDiskCacheContainsBlock)block
  453. {
  454. if (!key || !block)
  455. return;
  456. __weak PINDiskCache *weakSelf = self;
  457. [self.operationQueue addOperation:^{
  458. PINDiskCache *strongSelf = weakSelf;
  459. block([strongSelf containsObjectForKey:key]);
  460. } withPriority:PINOperationQueuePriorityLow];
  461. }
  462. - (void)objectForKey:(NSString *)key block:(PINDiskCacheObjectBlock)block
  463. {
  464. __weak PINDiskCache *weakSelf = self;
  465. [self.operationQueue addOperation:^{
  466. PINDiskCache *strongSelf = weakSelf;
  467. NSURL *fileURL = nil;
  468. id <NSCoding> object = [strongSelf objectForKey:key fileURL:&fileURL];
  469. if (block) {
  470. block(strongSelf, key, object);
  471. }
  472. } withPriority:PINOperationQueuePriorityLow];
  473. }
  474. - (void)fileURLForKey:(NSString *)key block:(PINDiskCacheFileURLBlock)block
  475. {
  476. __weak PINDiskCache *weakSelf = self;
  477. [self.operationQueue addOperation:^{
  478. PINDiskCache *strongSelf = weakSelf;
  479. NSURL *fileURL = [strongSelf fileURLForKey:key];
  480. if (block) {
  481. [strongSelf lock];
  482. block(key, fileURL);
  483. [strongSelf unlock];
  484. }
  485. } withPriority:PINOperationQueuePriorityLow];
  486. }
  487. - (void)setObject:(id <NSCoding>)object forKey:(NSString *)key block:(PINDiskCacheObjectBlock)block
  488. {
  489. __weak PINDiskCache *weakSelf = self;
  490. [self.operationQueue addOperation:^{
  491. PINDiskCache *strongSelf = weakSelf;
  492. NSURL *fileURL = nil;
  493. [strongSelf setObject:object forKey:key fileURL:&fileURL];
  494. if (block) {
  495. block(strongSelf, key, object);
  496. }
  497. } withPriority:PINOperationQueuePriorityLow];
  498. }
  499. - (void)removeObjectForKey:(NSString *)key block:(PINDiskCacheObjectBlock)block
  500. {
  501. __weak PINDiskCache *weakSelf = self;
  502. [self.operationQueue addOperation:^{
  503. PINDiskCache *strongSelf = weakSelf;
  504. NSURL *fileURL = nil;
  505. [strongSelf removeObjectForKey:key fileURL:&fileURL];
  506. if (block) {
  507. block(strongSelf, key, nil);
  508. }
  509. } withPriority:PINOperationQueuePriorityLow];
  510. }
  511. - (void)trimToSize:(NSUInteger)trimByteCount block:(PINDiskCacheBlock)block
  512. {
  513. __weak PINDiskCache *weakSelf = self;
  514. [self.operationQueue addOperation:^{
  515. PINDiskCache *strongSelf = weakSelf;
  516. [strongSelf trimToSize:trimByteCount];
  517. if (block) {
  518. block(strongSelf);
  519. }
  520. } withPriority:PINOperationQueuePriorityLow];
  521. }
  522. - (void)trimToDate:(NSDate *)trimDate block:(PINDiskCacheBlock)block
  523. {
  524. __weak PINDiskCache *weakSelf = self;
  525. [self.operationQueue addOperation:^{
  526. PINDiskCache *strongSelf = weakSelf;
  527. [strongSelf trimToDate:trimDate];
  528. if (block) {
  529. block(strongSelf);
  530. }
  531. } withPriority:PINOperationQueuePriorityLow];
  532. }
  533. - (void)trimToSizeByDate:(NSUInteger)trimByteCount block:(PINDiskCacheBlock)block
  534. {
  535. __weak PINDiskCache *weakSelf = self;
  536. [self.operationQueue addOperation:^{
  537. PINDiskCache *strongSelf = weakSelf;
  538. [strongSelf trimToSizeByDate:trimByteCount];
  539. if (block) {
  540. block(strongSelf);
  541. }
  542. } withPriority:PINOperationQueuePriorityLow];
  543. }
  544. - (void)removeAllObjects:(PINDiskCacheBlock)block
  545. {
  546. __weak PINDiskCache *weakSelf = self;
  547. [self.operationQueue addOperation:^{
  548. PINDiskCache *strongSelf = weakSelf;
  549. [strongSelf removeAllObjects];
  550. if (block) {
  551. block(strongSelf);
  552. }
  553. } withPriority:PINOperationQueuePriorityLow];
  554. }
  555. - (void)enumerateObjectsWithBlock:(PINDiskCacheFileURLBlock)block completionBlock:(PINDiskCacheBlock)completionBlock
  556. {
  557. __weak PINDiskCache *weakSelf = self;
  558. [self.operationQueue addOperation:^{
  559. PINDiskCache *strongSelf = weakSelf;
  560. [strongSelf enumerateObjectsWithBlock:block];
  561. if (completionBlock) {
  562. completionBlock(strongSelf);
  563. }
  564. } withPriority:PINOperationQueuePriorityLow];
  565. }
  566. #pragma mark - Public Synchronous Methods -
  567. - (void)synchronouslyLockFileAccessWhileExecutingBlock:(void(^)(PINDiskCache *diskCache))block
  568. {
  569. if (block) {
  570. [self lock];
  571. block(self);
  572. [self unlock];
  573. }
  574. }
  575. - (BOOL)containsObjectForKey:(NSString *)key
  576. {
  577. return ([self fileURLForKey:key updateFileModificationDate:NO] != nil);
  578. }
  579. - (__nullable id<NSCoding>)objectForKey:(NSString *)key
  580. {
  581. return [self objectForKey:key fileURL:nil];
  582. }
  583. - (id)objectForKeyedSubscript:(NSString *)key
  584. {
  585. return [self objectForKey:key];
  586. }
  587. - (__nullable id <NSCoding>)objectForKey:(NSString *)key fileURL:(NSURL **)outFileURL
  588. {
  589. NSDate *now = [[NSDate alloc] init];
  590. if (!key)
  591. return nil;
  592. id <NSCoding> object = nil;
  593. NSURL *fileURL = [self encodedFileURLForKey:key];
  594. [self lock];
  595. if (!self->_ttlCache || self->_ageLimit <= 0 || fabs([[_dates objectForKey:key] timeIntervalSinceDate:now]) < self->_ageLimit) {
  596. // If the cache should behave like a TTL cache, then only fetch the object if there's a valid ageLimit and the object is still alive
  597. NSData *objectData = [[NSData alloc] initWithContentsOfFile:[fileURL path]];
  598. if (objectData) {
  599. //Be careful with locking below. We unlock here so that we're not locked while deserializing, we re-lock after.
  600. [self unlock];
  601. @try {
  602. object = _deserializer(objectData, key);
  603. }
  604. @catch (NSException *exception) {
  605. NSError *error = nil;
  606. [self lock];
  607. [[NSFileManager defaultManager] removeItemAtPath:[fileURL path] error:&error];
  608. [self unlock];
  609. PINDiskCacheError(error);
  610. }
  611. [self lock];
  612. }
  613. if (object && !self->_ttlCache) {
  614. [self asynchronouslySetFileModificationDate:now forURL:fileURL];
  615. }
  616. }
  617. [self unlock];
  618. if (outFileURL) {
  619. *outFileURL = fileURL;
  620. }
  621. return object;
  622. }
  623. /// Helper function to call fileURLForKey:updateFileModificationDate:
  624. - (NSURL *)fileURLForKey:(NSString *)key
  625. {
  626. // Don't update the file modification time, if self is a ttlCache
  627. return [self fileURLForKey:key updateFileModificationDate:!self->_ttlCache];
  628. }
  629. - (NSURL *)fileURLForKey:(NSString *)key updateFileModificationDate:(BOOL)updateFileModificationDate
  630. {
  631. if (!key) {
  632. return nil;
  633. }
  634. NSDate *now = [[NSDate alloc] init];
  635. NSURL *fileURL = [self encodedFileURLForKey:key];
  636. [self lock];
  637. if ([[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) {
  638. if (updateFileModificationDate) {
  639. [self asynchronouslySetFileModificationDate:now forURL:fileURL];
  640. }
  641. } else {
  642. fileURL = nil;
  643. }
  644. [self unlock];
  645. return fileURL;
  646. }
  647. - (void)setObject:(id <NSCoding>)object forKey:(NSString *)key
  648. {
  649. [self setObject:object forKey:key fileURL:nil];
  650. }
  651. - (void)setObject:(id)object forKeyedSubscript:(NSString *)key
  652. {
  653. [self setObject:object forKey:key];
  654. }
  655. - (void)setObject:(id <NSCoding>)object forKey:(NSString *)key fileURL:(NSURL **)outFileURL
  656. {
  657. if (!key || !object)
  658. return;
  659. #if TARGET_OS_IPHONE
  660. NSDataWritingOptions writeOptions = NSDataWritingAtomic | self.writingProtectionOption;
  661. #else
  662. NSDataWritingOptions writeOptions = NSDataWritingAtomic;
  663. #endif
  664. NSURL *fileURL = [self encodedFileURLForKey:key];
  665. [self lock];
  666. PINDiskCacheObjectBlock willAddObjectBlock = self->_willAddObjectBlock;
  667. if (willAddObjectBlock) {
  668. [self unlock];
  669. willAddObjectBlock(self, key, object);
  670. [self lock];
  671. }
  672. //We unlock here so that we're not locked while serializing.
  673. [self unlock];
  674. NSData *data = _serializer(object, key);
  675. [self lock];
  676. NSError *writeError = nil;
  677. BOOL written = [data writeToURL:fileURL options:writeOptions error:&writeError];
  678. PINDiskCacheError(writeError);
  679. if (written) {
  680. NSError *error = nil;
  681. NSDictionary *values = [fileURL resourceValuesForKeys:@[ NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey ] error:&error];
  682. PINDiskCacheError(error);
  683. NSNumber *diskFileSize = [values objectForKey:NSURLTotalFileAllocatedSizeKey];
  684. if (diskFileSize) {
  685. NSNumber *prevDiskFileSize = [self->_sizes objectForKey:key];
  686. if (prevDiskFileSize) {
  687. self.byteCount = self->_byteCount - [prevDiskFileSize unsignedIntegerValue];
  688. }
  689. [self->_sizes setObject:diskFileSize forKey:key];
  690. self.byteCount = self->_byteCount + [diskFileSize unsignedIntegerValue]; // atomic
  691. }
  692. NSDate *date = [values objectForKey:NSURLContentModificationDateKey];
  693. if (date) {
  694. [self->_dates setObject:date forKey:key];
  695. }
  696. if (self->_byteLimit > 0 && self->_byteCount > self->_byteLimit)
  697. [self trimToSizeByDate:self->_byteLimit block:nil];
  698. } else {
  699. fileURL = nil;
  700. }
  701. PINDiskCacheObjectBlock didAddObjectBlock = self->_didAddObjectBlock;
  702. if (didAddObjectBlock) {
  703. [self unlock];
  704. didAddObjectBlock(self, key, object);
  705. [self lock];
  706. }
  707. [self unlock];
  708. if (outFileURL) {
  709. *outFileURL = fileURL;
  710. }
  711. }
  712. - (void)removeObjectForKey:(NSString *)key
  713. {
  714. [self removeObjectForKey:key fileURL:nil];
  715. }
  716. - (void)removeObjectForKey:(NSString *)key fileURL:(NSURL **)outFileURL
  717. {
  718. if (!key)
  719. return;
  720. NSURL *fileURL = nil;
  721. fileURL = [self encodedFileURLForKey:key];
  722. [self removeFileAndExecuteBlocksForKey:key];
  723. if (outFileURL) {
  724. *outFileURL = fileURL;
  725. }
  726. }
  727. - (void)trimToSize:(NSUInteger)trimByteCount
  728. {
  729. if (trimByteCount == 0) {
  730. [self removeAllObjects];
  731. return;
  732. }
  733. [self trimDiskToSize:trimByteCount];
  734. }
  735. - (void)trimToDate:(NSDate *)trimDate
  736. {
  737. if (!trimDate)
  738. return;
  739. if ([trimDate isEqualToDate:[NSDate distantPast]]) {
  740. [self removeAllObjects];
  741. return;
  742. }
  743. [self trimDiskToDate:trimDate];
  744. }
  745. - (void)trimToSizeByDate:(NSUInteger)trimByteCount
  746. {
  747. if (trimByteCount == 0) {
  748. [self removeAllObjects];
  749. return;
  750. }
  751. [self trimDiskToSizeByDate:trimByteCount];
  752. }
  753. - (void)removeAllObjects
  754. {
  755. [self lock];
  756. PINDiskCacheBlock willRemoveAllObjectsBlock = self->_willRemoveAllObjectsBlock;
  757. if (willRemoveAllObjectsBlock) {
  758. [self unlock];
  759. willRemoveAllObjectsBlock(self);
  760. [self lock];
  761. }
  762. [PINDiskCache moveItemAtURLToTrash:self->_cacheURL];
  763. [PINDiskCache emptyTrash];
  764. [self _locked_createCacheDirectory];
  765. [self->_dates removeAllObjects];
  766. [self->_sizes removeAllObjects];
  767. self.byteCount = 0; // atomic
  768. PINDiskCacheBlock didRemoveAllObjectsBlock = self->_didRemoveAllObjectsBlock;
  769. if (didRemoveAllObjectsBlock) {
  770. [self unlock];
  771. didRemoveAllObjectsBlock(self);
  772. [self lock];
  773. }
  774. [self unlock];
  775. }
  776. - (void)enumerateObjectsWithBlock:(PINDiskCacheFileURLBlock)block
  777. {
  778. if (!block)
  779. return;
  780. [self lock];
  781. NSDate *now = [NSDate date];
  782. NSArray *keysSortedByDate = [self->_dates keysSortedByValueUsingSelector:@selector(compare:)];
  783. for (NSString *key in keysSortedByDate) {
  784. NSURL *fileURL = [self encodedFileURLForKey:key];
  785. // If the cache should behave like a TTL cache, then only fetch the object if there's a valid ageLimit and the object is still alive
  786. if (!self->_ttlCache || self->_ageLimit <= 0 || fabs([[_dates objectForKey:key] timeIntervalSinceDate:now]) < self->_ageLimit) {
  787. block(key, fileURL);
  788. }
  789. }
  790. [self unlock];
  791. }
  792. #pragma mark - Public Thread Safe Accessors -
  793. - (PINDiskCacheObjectBlock)willAddObjectBlock
  794. {
  795. PINDiskCacheObjectBlock block = nil;
  796. [self lock];
  797. block = _willAddObjectBlock;
  798. [self unlock];
  799. return block;
  800. }
  801. - (void)setWillAddObjectBlock:(PINDiskCacheObjectBlock)block
  802. {
  803. __weak PINDiskCache *weakSelf = self;
  804. [self.operationQueue addOperation:^{
  805. PINDiskCache *strongSelf = weakSelf;
  806. if (!strongSelf)
  807. return;
  808. [strongSelf lock];
  809. strongSelf->_willAddObjectBlock = [block copy];
  810. [strongSelf unlock];
  811. } withPriority:PINOperationQueuePriorityHigh];
  812. }
  813. - (PINDiskCacheObjectBlock)willRemoveObjectBlock
  814. {
  815. PINDiskCacheObjectBlock block = nil;
  816. [self lock];
  817. block = _willRemoveObjectBlock;
  818. [self unlock];
  819. return block;
  820. }
  821. - (void)setWillRemoveObjectBlock:(PINDiskCacheObjectBlock)block
  822. {
  823. __weak PINDiskCache *weakSelf = self;
  824. [self.operationQueue addOperation:^{
  825. PINDiskCache *strongSelf = weakSelf;
  826. if (!strongSelf)
  827. return;
  828. [strongSelf lock];
  829. strongSelf->_willRemoveObjectBlock = [block copy];
  830. [strongSelf unlock];
  831. } withPriority:PINOperationQueuePriorityHigh];
  832. }
  833. - (PINDiskCacheBlock)willRemoveAllObjectsBlock
  834. {
  835. PINDiskCacheBlock block = nil;
  836. [self lock];
  837. block = _willRemoveAllObjectsBlock;
  838. [self unlock];
  839. return block;
  840. }
  841. - (void)setWillRemoveAllObjectsBlock:(PINDiskCacheBlock)block
  842. {
  843. __weak PINDiskCache *weakSelf = self;
  844. [self.operationQueue addOperation:^{
  845. PINDiskCache *strongSelf = weakSelf;
  846. if (!strongSelf)
  847. return;
  848. [strongSelf lock];
  849. strongSelf->_willRemoveAllObjectsBlock = [block copy];
  850. [strongSelf unlock];
  851. } withPriority:PINOperationQueuePriorityHigh];
  852. }
  853. - (PINDiskCacheObjectBlock)didAddObjectBlock
  854. {
  855. PINDiskCacheObjectBlock block = nil;
  856. [self lock];
  857. block = _didAddObjectBlock;
  858. [self unlock];
  859. return block;
  860. }
  861. - (void)setDidAddObjectBlock:(PINDiskCacheObjectBlock)block
  862. {
  863. __weak PINDiskCache *weakSelf = self;
  864. [self.operationQueue addOperation:^{
  865. PINDiskCache *strongSelf = weakSelf;
  866. if (!strongSelf)
  867. return;
  868. [strongSelf lock];
  869. strongSelf->_didAddObjectBlock = [block copy];
  870. [strongSelf unlock];
  871. } withPriority:PINOperationQueuePriorityHigh];
  872. }
  873. - (PINDiskCacheObjectBlock)didRemoveObjectBlock
  874. {
  875. PINDiskCacheObjectBlock block = nil;
  876. [self lock];
  877. block = _didRemoveObjectBlock;
  878. [self unlock];
  879. return block;
  880. }
  881. - (void)setDidRemoveObjectBlock:(PINDiskCacheObjectBlock)block
  882. {
  883. __weak PINDiskCache *weakSelf = self;
  884. [self.operationQueue addOperation:^{
  885. PINDiskCache *strongSelf = weakSelf;
  886. if (!strongSelf)
  887. return;
  888. [strongSelf lock];
  889. strongSelf->_didRemoveObjectBlock = [block copy];
  890. [strongSelf unlock];
  891. } withPriority:PINOperationQueuePriorityHigh];
  892. }
  893. - (PINDiskCacheBlock)didRemoveAllObjectsBlock
  894. {
  895. PINDiskCacheBlock block = nil;
  896. [self lock];
  897. block = _didRemoveAllObjectsBlock;
  898. [self unlock];
  899. return block;
  900. }
  901. - (void)setDidRemoveAllObjectsBlock:(PINDiskCacheBlock)block
  902. {
  903. __weak PINDiskCache *weakSelf = self;
  904. [self.operationQueue addOperation:^{
  905. PINDiskCache *strongSelf = weakSelf;
  906. if (!strongSelf)
  907. return;
  908. [strongSelf lock];
  909. strongSelf->_didRemoveAllObjectsBlock = [block copy];
  910. [strongSelf unlock];
  911. } withPriority:PINOperationQueuePriorityHigh];
  912. }
  913. - (NSUInteger)byteLimit
  914. {
  915. NSUInteger byteLimit;
  916. [self lock];
  917. byteLimit = _byteLimit;
  918. [self unlock];
  919. return byteLimit;
  920. }
  921. - (void)setByteLimit:(NSUInteger)byteLimit
  922. {
  923. __weak PINDiskCache *weakSelf = self;
  924. [self.operationQueue addOperation:^{
  925. PINDiskCache *strongSelf = weakSelf;
  926. if (!strongSelf)
  927. return;
  928. [strongSelf lock];
  929. strongSelf->_byteLimit = byteLimit;
  930. [strongSelf unlock];
  931. if (byteLimit > 0)
  932. [strongSelf trimDiskToSizeByDate:byteLimit];
  933. } withPriority:PINOperationQueuePriorityHigh];
  934. }
  935. - (NSTimeInterval)ageLimit
  936. {
  937. NSTimeInterval ageLimit;
  938. [self lock];
  939. ageLimit = _ageLimit;
  940. [self unlock];
  941. return ageLimit;
  942. }
  943. - (void)setAgeLimit:(NSTimeInterval)ageLimit
  944. {
  945. __weak PINDiskCache *weakSelf = self;
  946. [self.operationQueue addOperation:^{
  947. PINDiskCache *strongSelf = weakSelf;
  948. if (!strongSelf)
  949. return;
  950. [strongSelf lock];
  951. strongSelf->_ageLimit = ageLimit;
  952. [strongSelf unlock];
  953. [strongSelf trimToAgeLimitRecursively];
  954. } withPriority:PINOperationQueuePriorityHigh];
  955. }
  956. - (BOOL)isTTLCache {
  957. BOOL isTTLCache;
  958. [self lock];
  959. isTTLCache = _ttlCache;
  960. [self unlock];
  961. return isTTLCache;
  962. }
  963. - (void)setTtlCache:(BOOL)ttlCache {
  964. __weak PINDiskCache *weakSelf = self;
  965. [self.operationQueue addOperation:^{
  966. PINDiskCache *strongSelf = weakSelf;
  967. if (!strongSelf)
  968. return;
  969. [strongSelf lock];
  970. strongSelf->_ttlCache = ttlCache;
  971. [strongSelf unlock];
  972. } withPriority:PINOperationQueuePriorityHigh];
  973. }
  974. #if TARGET_OS_IPHONE
  975. - (NSDataWritingOptions)writingProtectionOption {
  976. NSDataWritingOptions option;
  977. [self lock];
  978. option = _writingProtectionOption;
  979. [self unlock];
  980. return option;
  981. }
  982. - (void)setWritingProtectionOption:(NSDataWritingOptions)writingProtectionOption {
  983. __weak PINDiskCache *weakSelf = self;
  984. [self.operationQueue addOperation:^{
  985. PINDiskCache *strongSelf = weakSelf;
  986. if (!strongSelf)
  987. return;
  988. NSDataWritingOptions option = NSDataWritingFileProtectionMask & writingProtectionOption;
  989. [strongSelf lock];
  990. strongSelf->_writingProtectionOption = option;
  991. [strongSelf unlock];
  992. } withPriority:PINOperationQueuePriorityHigh];
  993. }
  994. #endif
  995. - (void)lock
  996. {
  997. [_instanceLock lockWhenCondition:PINDiskCacheConditionReady];
  998. }
  999. - (void)unlock
  1000. {
  1001. [_instanceLock unlockWithCondition:PINDiskCacheConditionReady];
  1002. }
  1003. @end