PINDiskCache.m 43 KB

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