PINDiskCache.m 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  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. #define PINDiskCacheError(error) if (error) { NSLog(@"%@ (%d) ERROR: %@", \
  9. [[NSString stringWithUTF8String:__FILE__] lastPathComponent], \
  10. __LINE__, [error localizedDescription]); }
  11. static NSString * const PINDiskCachePrefix = @"com.pinterest.PINDiskCache";
  12. static NSString * const PINDiskCacheSharedName = @"PINDiskCacheShared";
  13. @interface PINBackgroundTask : NSObject
  14. #if !defined(PIN_APP_EXTENSIONS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0
  15. @property (atomic, assign) UIBackgroundTaskIdentifier taskID;
  16. #endif
  17. + (instancetype)start;
  18. - (void)end;
  19. @end
  20. @interface PINDiskCache ()
  21. @property (assign) NSUInteger byteCount;
  22. @property (strong, nonatomic) NSURL *cacheURL;
  23. #if OS_OBJECT_USE_OBJC
  24. @property (strong, nonatomic) dispatch_queue_t asyncQueue;
  25. @property (strong, nonatomic) dispatch_semaphore_t lockSemaphore;
  26. #else
  27. @property (assign, nonatomic) dispatch_queue_t asyncQueue;
  28. @property (assign, nonatomic) dispatch_semaphore_t lockSemaphore;
  29. #endif
  30. @property (strong, nonatomic) NSMutableDictionary *dates;
  31. @property (strong, nonatomic) NSMutableDictionary *sizes;
  32. @end
  33. @implementation PINDiskCache
  34. @synthesize willAddObjectBlock = _willAddObjectBlock;
  35. @synthesize willRemoveObjectBlock = _willRemoveObjectBlock;
  36. @synthesize willRemoveAllObjectsBlock = _willRemoveAllObjectsBlock;
  37. @synthesize didAddObjectBlock = _didAddObjectBlock;
  38. @synthesize didRemoveObjectBlock = _didRemoveObjectBlock;
  39. @synthesize didRemoveAllObjectsBlock = _didRemoveAllObjectsBlock;
  40. @synthesize byteLimit = _byteLimit;
  41. @synthesize ageLimit = _ageLimit;
  42. #pragma mark - Initialization -
  43. - (void)dealloc
  44. {
  45. #if !OS_OBJECT_USE_OBJC
  46. dispatch_release(_lockSemaphore);
  47. dispatch_release(_asyncQueue);
  48. _asyncQueue = nil;
  49. #endif
  50. }
  51. - (instancetype)init
  52. {
  53. @throw [NSException exceptionWithName:@"Must initialize with a name" reason:@"PINDiskCache must be initialized with a name. Call initWithName: instead." userInfo:nil];
  54. return [self initWithName:@""];
  55. }
  56. - (instancetype)initWithName:(NSString *)name
  57. {
  58. return [self initWithName:name rootPath:[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
  59. }
  60. - (instancetype)initWithName:(NSString *)name rootPath:(NSString *)rootPath
  61. {
  62. if (!name)
  63. return nil;
  64. if (self = [super init]) {
  65. _name = [name copy];
  66. _asyncQueue = dispatch_queue_create([[NSString stringWithFormat:@"%@ Asynchronous Queue", PINDiskCachePrefix] UTF8String], DISPATCH_QUEUE_CONCURRENT);
  67. _lockSemaphore = dispatch_semaphore_create(1);
  68. _willAddObjectBlock = nil;
  69. _willRemoveObjectBlock = nil;
  70. _willRemoveAllObjectsBlock = nil;
  71. _didAddObjectBlock = nil;
  72. _didRemoveObjectBlock = nil;
  73. _didRemoveAllObjectsBlock = nil;
  74. _byteCount = 0;
  75. _byteLimit = 0;
  76. _ageLimit = 0.0;
  77. _dates = [[NSMutableDictionary alloc] init];
  78. _sizes = [[NSMutableDictionary alloc] init];
  79. NSString *pathComponent = [[NSString alloc] initWithFormat:@"%@.%@", PINDiskCachePrefix, _name];
  80. _cacheURL = [NSURL fileURLWithPathComponents:@[ rootPath, pathComponent ]];
  81. [self createCacheDirectory];
  82. [self initializeDiskProperties];
  83. }
  84. return self;
  85. }
  86. - (NSString *)description
  87. {
  88. return [[NSString alloc] initWithFormat:@"%@.%@.%p", PINDiskCachePrefix, _name, self];
  89. }
  90. + (instancetype)sharedCache
  91. {
  92. static id cache;
  93. static dispatch_once_t predicate;
  94. dispatch_once(&predicate, ^{
  95. cache = [[self alloc] initWithName:PINDiskCacheSharedName];
  96. });
  97. return cache;
  98. }
  99. #pragma mark - Private Methods -
  100. - (NSURL *)encodedFileURLForKey:(NSString *)key
  101. {
  102. if (![key length])
  103. return nil;
  104. return [_cacheURL URLByAppendingPathComponent:[self encodedString:key]];
  105. }
  106. - (NSString *)keyForEncodedFileURL:(NSURL *)url
  107. {
  108. NSString *fileName = [url lastPathComponent];
  109. if (!fileName)
  110. return nil;
  111. return [self decodedString:fileName];
  112. }
  113. - (NSString *)encodedString:(NSString *)string
  114. {
  115. if (![string length]) {
  116. return @"";
  117. }
  118. if ([string respondsToSelector:@selector(stringByAddingPercentEncodingWithAllowedCharacters:)]) {
  119. return [string stringByAddingPercentEncodingWithAllowedCharacters:[[NSCharacterSet characterSetWithCharactersInString:@".:/"] invertedSet]];
  120. }
  121. else {
  122. CFStringRef static const charsToEscape = CFSTR(".:/");
  123. #pragma clang diagnostic push
  124. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  125. CFStringRef escapedString = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
  126. (__bridge CFStringRef)string,
  127. NULL,
  128. charsToEscape,
  129. kCFStringEncodingUTF8);
  130. #pragma clang diagnostic pop
  131. return (__bridge_transfer NSString *)escapedString;
  132. }
  133. }
  134. - (NSString *)decodedString:(NSString *)string
  135. {
  136. if (![string length]) {
  137. return @"";
  138. }
  139. if ([string respondsToSelector:@selector(stringByRemovingPercentEncoding)]) {
  140. return [string stringByRemovingPercentEncoding];
  141. }
  142. else {
  143. #pragma clang diagnostic push
  144. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  145. CFStringRef unescapedString = CFURLCreateStringByReplacingPercentEscapesUsingEncoding(kCFAllocatorDefault,
  146. (__bridge CFStringRef)string,
  147. CFSTR(""),
  148. kCFStringEncodingUTF8);
  149. #pragma clang diagnostic pop
  150. return (__bridge_transfer NSString *)unescapedString;
  151. }
  152. }
  153. #pragma mark - Private Trash Methods -
  154. + (dispatch_queue_t)sharedTrashQueue
  155. {
  156. static dispatch_queue_t trashQueue;
  157. static dispatch_once_t predicate;
  158. dispatch_once(&predicate, ^{
  159. NSString *queueName = [[NSString alloc] initWithFormat:@"%@.trash", PINDiskCachePrefix];
  160. trashQueue = dispatch_queue_create([queueName UTF8String], DISPATCH_QUEUE_SERIAL);
  161. dispatch_set_target_queue(trashQueue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0));
  162. });
  163. return trashQueue;
  164. }
  165. + (NSURL *)sharedTrashURL
  166. {
  167. static NSURL *sharedTrashURL;
  168. static dispatch_once_t predicate;
  169. dispatch_once(&predicate, ^{
  170. sharedTrashURL = [[[NSURL alloc] initFileURLWithPath:NSTemporaryDirectory()] URLByAppendingPathComponent:PINDiskCachePrefix isDirectory:YES];
  171. if (![[NSFileManager defaultManager] fileExistsAtPath:[sharedTrashURL path]]) {
  172. NSError *error = nil;
  173. [[NSFileManager defaultManager] createDirectoryAtURL:sharedTrashURL
  174. withIntermediateDirectories:YES
  175. attributes:nil
  176. error:&error];
  177. PINDiskCacheError(error);
  178. }
  179. });
  180. return sharedTrashURL;
  181. }
  182. +(BOOL)moveItemAtURLToTrash:(NSURL *)itemURL
  183. {
  184. if (![[NSFileManager defaultManager] fileExistsAtPath:[itemURL path]])
  185. return NO;
  186. NSError *error = nil;
  187. NSString *uniqueString = [[NSProcessInfo processInfo] globallyUniqueString];
  188. NSURL *uniqueTrashURL = [[PINDiskCache sharedTrashURL] URLByAppendingPathComponent:uniqueString];
  189. BOOL moved = [[NSFileManager defaultManager] moveItemAtURL:itemURL toURL:uniqueTrashURL error:&error];
  190. PINDiskCacheError(error);
  191. return moved;
  192. }
  193. + (void)emptyTrash
  194. {
  195. PINBackgroundTask *task = [PINBackgroundTask start];
  196. dispatch_async([self sharedTrashQueue], ^{
  197. NSError *searchTrashedItemsError = nil;
  198. NSArray *trashedItems = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:[self sharedTrashURL]
  199. includingPropertiesForKeys:nil
  200. options:0
  201. error:&searchTrashedItemsError];
  202. PINDiskCacheError(searchTrashedItemsError);
  203. for (NSURL *trashedItemURL in trashedItems) {
  204. NSError *removeTrashedItemError = nil;
  205. [[NSFileManager defaultManager] removeItemAtURL:trashedItemURL error:&removeTrashedItemError];
  206. PINDiskCacheError(removeTrashedItemError);
  207. }
  208. [task end];
  209. });
  210. }
  211. #pragma mark - Private Queue Methods -
  212. - (BOOL)createCacheDirectory
  213. {
  214. if ([[NSFileManager defaultManager] fileExistsAtPath:[_cacheURL path]])
  215. return NO;
  216. NSError *error = nil;
  217. BOOL success = [[NSFileManager defaultManager] createDirectoryAtURL:_cacheURL
  218. withIntermediateDirectories:YES
  219. attributes:nil
  220. error:&error];
  221. PINDiskCacheError(error);
  222. return success;
  223. }
  224. - (void)initializeDiskProperties
  225. {
  226. NSUInteger byteCount = 0;
  227. NSArray *keys = @[ NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey ];
  228. NSError *error = nil;
  229. NSArray *files = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:_cacheURL
  230. includingPropertiesForKeys:keys
  231. options:NSDirectoryEnumerationSkipsHiddenFiles
  232. error:&error];
  233. PINDiskCacheError(error);
  234. for (NSURL *fileURL in files) {
  235. NSString *key = [self keyForEncodedFileURL:fileURL];
  236. error = nil;
  237. NSDictionary *dictionary = [fileURL resourceValuesForKeys:keys error:&error];
  238. PINDiskCacheError(error);
  239. NSDate *date = [dictionary objectForKey:NSURLContentModificationDateKey];
  240. if (date && key)
  241. [_dates setObject:date forKey:key];
  242. NSNumber *fileSize = [dictionary objectForKey:NSURLTotalFileAllocatedSizeKey];
  243. if (fileSize) {
  244. [_sizes setObject:fileSize forKey:key];
  245. byteCount += [fileSize unsignedIntegerValue];
  246. }
  247. }
  248. if (byteCount > 0)
  249. self.byteCount = byteCount; // atomic
  250. }
  251. - (BOOL)setFileModificationDate:(NSDate *)date forURL:(NSURL *)fileURL
  252. {
  253. if (!date || !fileURL) {
  254. return NO;
  255. }
  256. NSError *error = nil;
  257. BOOL success = [[NSFileManager defaultManager] setAttributes:@{ NSFileModificationDate: date }
  258. ofItemAtPath:[fileURL path]
  259. error:&error];
  260. PINDiskCacheError(error);
  261. if (success) {
  262. NSString *key = [self keyForEncodedFileURL:fileURL];
  263. if (key) {
  264. [_dates setObject:date forKey:key];
  265. }
  266. }
  267. return success;
  268. }
  269. - (BOOL)removeFileAndExecuteBlocksForKey:(NSString *)key
  270. {
  271. NSURL *fileURL = [self encodedFileURLForKey:key];
  272. if (!fileURL || ![[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]])
  273. return NO;
  274. if (_willRemoveObjectBlock)
  275. _willRemoveObjectBlock(self, key, nil, fileURL);
  276. BOOL trashed = [PINDiskCache moveItemAtURLToTrash:fileURL];
  277. if (!trashed)
  278. return NO;
  279. [PINDiskCache emptyTrash];
  280. NSNumber *byteSize = [_sizes objectForKey:key];
  281. if (byteSize)
  282. self.byteCount = _byteCount - [byteSize unsignedIntegerValue]; // atomic
  283. [_sizes removeObjectForKey:key];
  284. [_dates removeObjectForKey:key];
  285. if (_didRemoveObjectBlock)
  286. _didRemoveObjectBlock(self, key, nil, fileURL);
  287. return YES;
  288. }
  289. - (void)trimDiskToSize:(NSUInteger)trimByteCount
  290. {
  291. if (_byteCount <= trimByteCount)
  292. return;
  293. NSArray *keysSortedBySize = [_sizes keysSortedByValueUsingSelector:@selector(compare:)];
  294. for (NSString *key in [keysSortedBySize reverseObjectEnumerator]) { // largest objects first
  295. [self removeFileAndExecuteBlocksForKey:key];
  296. if (_byteCount <= trimByteCount)
  297. break;
  298. }
  299. }
  300. - (void)trimDiskToSizeByDate:(NSUInteger)trimByteCount
  301. {
  302. if (_byteCount <= trimByteCount)
  303. return;
  304. NSArray *keysSortedByDate = [_dates keysSortedByValueUsingSelector:@selector(compare:)];
  305. for (NSString *key in keysSortedByDate) { // oldest objects first
  306. [self removeFileAndExecuteBlocksForKey:key];
  307. if (_byteCount <= trimByteCount)
  308. break;
  309. }
  310. }
  311. - (void)trimDiskToDate:(NSDate *)trimDate
  312. {
  313. NSArray *keysSortedByDate = [_dates keysSortedByValueUsingSelector:@selector(compare:)];
  314. for (NSString *key in keysSortedByDate) { // oldest files first
  315. NSDate *accessDate = [_dates objectForKey:key];
  316. if (!accessDate)
  317. continue;
  318. if ([accessDate compare:trimDate] == NSOrderedAscending) { // older than trim date
  319. [self removeFileAndExecuteBlocksForKey:key];
  320. } else {
  321. break;
  322. }
  323. }
  324. }
  325. - (void)trimToAgeLimitRecursively
  326. {
  327. [self lock];
  328. NSTimeInterval ageLimit = _ageLimit;
  329. [self unlock];
  330. if (ageLimit == 0.0)
  331. return;
  332. [self lock];
  333. NSDate *date = [[NSDate alloc] initWithTimeIntervalSinceNow:-ageLimit];
  334. [self trimDiskToDate:date];
  335. [self unlock];
  336. __weak PINDiskCache *weakSelf = self;
  337. dispatch_time_t time = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_ageLimit * NSEC_PER_SEC));
  338. dispatch_after(time, _asyncQueue, ^(void) {
  339. PINDiskCache *strongSelf = weakSelf;
  340. [strongSelf trimToAgeLimitRecursively];
  341. });
  342. }
  343. #pragma mark - Public Asynchronous Methods -
  344. - (void)lockFileAccessWhileExecutingBlock:(void(^)(PINDiskCache *diskCache))block
  345. {
  346. __weak PINDiskCache *weakSelf = self;
  347. dispatch_async(_asyncQueue, ^{
  348. PINDiskCache *strongSelf = weakSelf;
  349. if (block) {
  350. [strongSelf lock];
  351. block(strongSelf);
  352. [strongSelf unlock];
  353. }
  354. });
  355. }
  356. - (void)objectForKey:(NSString *)key block:(PINDiskCacheObjectBlock)block
  357. {
  358. __weak PINDiskCache *weakSelf = self;
  359. dispatch_async(_asyncQueue, ^{
  360. PINDiskCache *strongSelf = weakSelf;
  361. NSURL *fileURL = nil;
  362. id <NSCoding> object = [strongSelf objectForKey:key fileURL:&fileURL];
  363. if (block) {
  364. [strongSelf lock];
  365. block(strongSelf, key, object, fileURL);
  366. [strongSelf unlock];
  367. }
  368. });
  369. }
  370. - (void)fileURLForKey:(NSString *)key block:(PINDiskCacheObjectBlock)block
  371. {
  372. __weak PINDiskCache *weakSelf = self;
  373. dispatch_async(_asyncQueue, ^{
  374. PINDiskCache *strongSelf = weakSelf;
  375. NSURL *fileURL = [strongSelf fileURLForKey:key];
  376. if (block) {
  377. [strongSelf lock];
  378. block(strongSelf, key, nil, fileURL);
  379. [strongSelf unlock];
  380. }
  381. });
  382. }
  383. - (void)setObject:(id <NSCoding>)object forKey:(NSString *)key block:(PINDiskCacheObjectBlock)block
  384. {
  385. __weak PINDiskCache *weakSelf = self;
  386. dispatch_async(_asyncQueue, ^{
  387. PINDiskCache *strongSelf = weakSelf;
  388. NSURL *fileURL = nil;
  389. [strongSelf setObject:object forKey:key fileURL:&fileURL];
  390. if (block) {
  391. [strongSelf lock];
  392. block(strongSelf, key, object, fileURL);
  393. [strongSelf unlock];
  394. }
  395. });
  396. }
  397. - (void)removeObjectForKey:(NSString *)key block:(PINDiskCacheObjectBlock)block
  398. {
  399. __weak PINDiskCache *weakSelf = self;
  400. dispatch_async(_asyncQueue, ^{
  401. PINDiskCache *strongSelf = weakSelf;
  402. NSURL *fileURL = nil;
  403. [strongSelf removeObjectForKey:key fileURL:&fileURL];
  404. if (block) {
  405. [strongSelf lock];
  406. block(strongSelf, key, nil, fileURL);
  407. [strongSelf unlock];
  408. }
  409. });
  410. }
  411. - (void)trimToSize:(NSUInteger)trimByteCount block:(PINDiskCacheBlock)block
  412. {
  413. __weak PINDiskCache *weakSelf = self;
  414. dispatch_async(_asyncQueue, ^{
  415. PINDiskCache *strongSelf = weakSelf;
  416. [strongSelf trimToSize:trimByteCount];
  417. if (block) {
  418. [strongSelf lock];
  419. block(strongSelf);
  420. [strongSelf unlock];
  421. }
  422. });
  423. }
  424. - (void)trimToDate:(NSDate *)trimDate block:(PINDiskCacheBlock)block
  425. {
  426. __weak PINDiskCache *weakSelf = self;
  427. dispatch_async(_asyncQueue, ^{
  428. PINDiskCache *strongSelf = weakSelf;
  429. [strongSelf trimToDate:trimDate];
  430. if (block) {
  431. [strongSelf lock];
  432. block(strongSelf);
  433. [strongSelf unlock];
  434. }
  435. });
  436. }
  437. - (void)trimToSizeByDate:(NSUInteger)trimByteCount block:(PINDiskCacheBlock)block
  438. {
  439. __weak PINDiskCache *weakSelf = self;
  440. dispatch_async(_asyncQueue, ^{
  441. PINDiskCache *strongSelf = weakSelf;
  442. [strongSelf trimToSizeByDate:trimByteCount];
  443. if (block) {
  444. [strongSelf lock];
  445. block(strongSelf);
  446. [strongSelf unlock];
  447. }
  448. });
  449. }
  450. - (void)removeAllObjects:(PINDiskCacheBlock)block
  451. {
  452. __weak PINDiskCache *weakSelf = self;
  453. dispatch_async(_asyncQueue, ^{
  454. PINDiskCache *strongSelf = weakSelf;
  455. [strongSelf removeAllObjects];
  456. if (block) {
  457. [strongSelf lock];
  458. block(strongSelf);
  459. [strongSelf unlock];
  460. }
  461. });
  462. }
  463. - (void)enumerateObjectsWithBlock:(PINDiskCacheObjectBlock)block completionBlock:(PINDiskCacheBlock)completionBlock
  464. {
  465. __weak PINDiskCache *weakSelf = self;
  466. dispatch_async(_asyncQueue, ^{
  467. PINDiskCache *strongSelf = weakSelf;
  468. [strongSelf enumerateObjectsWithBlock:block];
  469. if (completionBlock) {
  470. [self lock];
  471. completionBlock(strongSelf);
  472. [self unlock];
  473. }
  474. });
  475. }
  476. #pragma mark - Public Synchronous Methods -
  477. - (void)synchronouslyLockFileAccessWhileExecutingBlock:(void(^)(PINDiskCache *diskCache))block
  478. {
  479. if (block) {
  480. [self lock];
  481. block(self);
  482. [self unlock];
  483. }
  484. }
  485. - (__nullable id<NSCoding>)objectForKey:(NSString *)key
  486. {
  487. return [self objectForKey:key fileURL:nil];
  488. }
  489. - (__nullable id <NSCoding>)objectForKey:(NSString *)key fileURL:(NSURL **)outFileURL
  490. {
  491. NSDate *now = [[NSDate alloc] init];
  492. if (!key)
  493. return nil;
  494. id <NSCoding> object = nil;
  495. NSURL *fileURL = nil;
  496. [self lock];
  497. fileURL = [self encodedFileURLForKey:key];
  498. object = nil;
  499. if ([[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) {
  500. @try {
  501. object = [NSKeyedUnarchiver unarchiveObjectWithFile:[fileURL path]];
  502. }
  503. @catch (NSException *exception) {
  504. NSError *error = nil;
  505. [[NSFileManager defaultManager] removeItemAtPath:[fileURL path] error:&error];
  506. PINDiskCacheError(error);
  507. }
  508. [self setFileModificationDate:now forURL:fileURL];
  509. }
  510. [self unlock];
  511. if (outFileURL) {
  512. *outFileURL = fileURL;
  513. }
  514. return object;
  515. }
  516. - (NSURL *)fileURLForKey:(NSString *)key
  517. {
  518. NSDate *now = [[NSDate alloc] init];
  519. if (!key)
  520. return nil;
  521. NSURL *fileURL = nil;
  522. [self lock];
  523. fileURL = [self encodedFileURLForKey:key];
  524. if ([[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) {
  525. [self setFileModificationDate:now forURL:fileURL];
  526. } else {
  527. fileURL = nil;
  528. }
  529. [self unlock];
  530. return fileURL;
  531. }
  532. - (void)setObject:(id <NSCoding>)object forKey:(NSString *)key
  533. {
  534. [self setObject:object forKey:key fileURL:nil];
  535. }
  536. - (void)setObject:(id <NSCoding>)object forKey:(NSString *)key fileURL:(NSURL **)outFileURL
  537. {
  538. NSDate *now = [[NSDate alloc] init];
  539. if (!key || !object)
  540. return;
  541. PINBackgroundTask *task = [PINBackgroundTask start];
  542. NSURL *fileURL = nil;
  543. [self lock];
  544. fileURL = [self encodedFileURLForKey:key];
  545. if (self->_willAddObjectBlock)
  546. self->_willAddObjectBlock(self, key, object, fileURL);
  547. BOOL written = [NSKeyedArchiver archiveRootObject:object toFile:[fileURL path]];
  548. if (written) {
  549. [self setFileModificationDate:now forURL:fileURL];
  550. NSError *error = nil;
  551. NSDictionary *values = [fileURL resourceValuesForKeys:@[ NSURLTotalFileAllocatedSizeKey ] error:&error];
  552. PINDiskCacheError(error);
  553. NSNumber *diskFileSize = [values objectForKey:NSURLTotalFileAllocatedSizeKey];
  554. if (diskFileSize) {
  555. NSNumber *prevDiskFileSize = [self->_sizes objectForKey:key];
  556. if (prevDiskFileSize) {
  557. self.byteCount = self->_byteCount - [prevDiskFileSize unsignedIntegerValue];
  558. }
  559. [self->_sizes setObject:diskFileSize forKey:key];
  560. self.byteCount = self->_byteCount + [diskFileSize unsignedIntegerValue]; // atomic
  561. }
  562. if (self->_byteLimit > 0 && self->_byteCount > self->_byteLimit)
  563. [self trimToSizeByDate:self->_byteLimit block:nil];
  564. } else {
  565. fileURL = nil;
  566. }
  567. if (self->_didAddObjectBlock)
  568. self->_didAddObjectBlock(self, key, object, written ? fileURL : nil);
  569. [self unlock];
  570. if (outFileURL) {
  571. *outFileURL = fileURL;
  572. }
  573. [task end];
  574. }
  575. - (void)removeObjectForKey:(NSString *)key
  576. {
  577. [self removeObjectForKey:key fileURL:nil];
  578. }
  579. - (void)removeObjectForKey:(NSString *)key fileURL:(NSURL **)outFileURL
  580. {
  581. if (!key)
  582. return;
  583. PINBackgroundTask *task = [PINBackgroundTask start];
  584. NSURL *fileURL = nil;
  585. [self lock];
  586. fileURL = [self encodedFileURLForKey:key];
  587. [self removeFileAndExecuteBlocksForKey:key];
  588. [self unlock];
  589. [task end];
  590. if (outFileURL) {
  591. *outFileURL = fileURL;
  592. }
  593. }
  594. - (void)trimToSize:(NSUInteger)trimByteCount
  595. {
  596. if (trimByteCount == 0) {
  597. [self removeAllObjects];
  598. return;
  599. }
  600. PINBackgroundTask *task = [PINBackgroundTask start];
  601. [self lock];
  602. [self trimDiskToSize:trimByteCount];
  603. [self unlock];
  604. [task end];
  605. }
  606. - (void)trimToDate:(NSDate *)trimDate
  607. {
  608. if (!trimDate)
  609. return;
  610. if ([trimDate isEqualToDate:[NSDate distantPast]]) {
  611. [self removeAllObjects];
  612. return;
  613. }
  614. PINBackgroundTask *task = [PINBackgroundTask start];
  615. [self lock];
  616. [self trimDiskToDate:trimDate];
  617. [self unlock];
  618. [task end];
  619. }
  620. - (void)trimToSizeByDate:(NSUInteger)trimByteCount
  621. {
  622. if (trimByteCount == 0) {
  623. [self removeAllObjects];
  624. return;
  625. }
  626. PINBackgroundTask *task = [PINBackgroundTask start];
  627. [self lock];
  628. [self trimDiskToSizeByDate:trimByteCount];
  629. [self unlock];
  630. [task end];
  631. }
  632. - (void)removeAllObjects
  633. {
  634. PINBackgroundTask *task = [PINBackgroundTask start];
  635. [self lock];
  636. if (self->_willRemoveAllObjectsBlock)
  637. self->_willRemoveAllObjectsBlock(self);
  638. [PINDiskCache moveItemAtURLToTrash:self->_cacheURL];
  639. [PINDiskCache emptyTrash];
  640. [self createCacheDirectory];
  641. [self->_dates removeAllObjects];
  642. [self->_sizes removeAllObjects];
  643. self.byteCount = 0; // atomic
  644. if (self->_didRemoveAllObjectsBlock)
  645. self->_didRemoveAllObjectsBlock(self);
  646. [self unlock];
  647. [task end];
  648. }
  649. - (void)enumerateObjectsWithBlock:(PINDiskCacheObjectBlock)block
  650. {
  651. if (!block)
  652. return;
  653. PINBackgroundTask *task = [PINBackgroundTask start];
  654. [self lock];
  655. NSArray *keysSortedByDate = [self->_dates keysSortedByValueUsingSelector:@selector(compare:)];
  656. for (NSString *key in keysSortedByDate) {
  657. NSURL *fileURL = [self encodedFileURLForKey:key];
  658. block(self, key, nil, fileURL);
  659. }
  660. [self unlock];
  661. [task end];
  662. }
  663. #pragma mark - Public Thread Safe Accessors -
  664. - (PINDiskCacheObjectBlock)willAddObjectBlock
  665. {
  666. PINDiskCacheObjectBlock block = nil;
  667. [self lock];
  668. block = _willAddObjectBlock;
  669. [self unlock];
  670. return block;
  671. }
  672. - (void)setWillAddObjectBlock:(PINDiskCacheObjectBlock)block
  673. {
  674. __weak PINDiskCache *weakSelf = self;
  675. dispatch_async(_asyncQueue, ^{
  676. PINDiskCache *strongSelf = weakSelf;
  677. if (!strongSelf)
  678. return;
  679. [strongSelf lock];
  680. strongSelf->_willAddObjectBlock = [block copy];
  681. [strongSelf unlock];
  682. });
  683. }
  684. - (PINDiskCacheObjectBlock)willRemoveObjectBlock
  685. {
  686. PINDiskCacheObjectBlock block = nil;
  687. [self lock];
  688. block = _willRemoveObjectBlock;
  689. [self unlock];
  690. return block;
  691. }
  692. - (void)setWillRemoveObjectBlock:(PINDiskCacheObjectBlock)block
  693. {
  694. __weak PINDiskCache *weakSelf = self;
  695. dispatch_async(_asyncQueue, ^{
  696. PINDiskCache *strongSelf = weakSelf;
  697. if (!strongSelf)
  698. return;
  699. [strongSelf lock];
  700. strongSelf->_willRemoveObjectBlock = [block copy];
  701. [strongSelf unlock];
  702. });
  703. }
  704. - (PINDiskCacheBlock)willRemoveAllObjectsBlock
  705. {
  706. PINDiskCacheBlock block = nil;
  707. [self lock];
  708. block = _willRemoveAllObjectsBlock;
  709. [self unlock];
  710. return block;
  711. }
  712. - (void)setWillRemoveAllObjectsBlock:(PINDiskCacheBlock)block
  713. {
  714. __weak PINDiskCache *weakSelf = self;
  715. dispatch_async(_asyncQueue, ^{
  716. PINDiskCache *strongSelf = weakSelf;
  717. if (!strongSelf)
  718. return;
  719. [strongSelf lock];
  720. strongSelf->_willRemoveAllObjectsBlock = [block copy];
  721. [strongSelf unlock];
  722. });
  723. }
  724. - (PINDiskCacheObjectBlock)didAddObjectBlock
  725. {
  726. PINDiskCacheObjectBlock block = nil;
  727. [self lock];
  728. block = _didAddObjectBlock;
  729. [self unlock];
  730. return block;
  731. }
  732. - (void)setDidAddObjectBlock:(PINDiskCacheObjectBlock)block
  733. {
  734. __weak PINDiskCache *weakSelf = self;
  735. dispatch_async(_asyncQueue, ^{
  736. PINDiskCache *strongSelf = weakSelf;
  737. if (!strongSelf)
  738. return;
  739. [strongSelf lock];
  740. strongSelf->_didAddObjectBlock = [block copy];
  741. [strongSelf unlock];
  742. });
  743. }
  744. - (PINDiskCacheObjectBlock)didRemoveObjectBlock
  745. {
  746. PINDiskCacheObjectBlock block = nil;
  747. [self lock];
  748. block = _didRemoveObjectBlock;
  749. [self unlock];
  750. return block;
  751. }
  752. - (void)setDidRemoveObjectBlock:(PINDiskCacheObjectBlock)block
  753. {
  754. __weak PINDiskCache *weakSelf = self;
  755. dispatch_async(_asyncQueue, ^{
  756. PINDiskCache *strongSelf = weakSelf;
  757. if (!strongSelf)
  758. return;
  759. [strongSelf lock];
  760. strongSelf->_didRemoveObjectBlock = [block copy];
  761. [strongSelf unlock];
  762. });
  763. }
  764. - (PINDiskCacheBlock)didRemoveAllObjectsBlock
  765. {
  766. PINDiskCacheBlock block = nil;
  767. [self lock];
  768. block = _didRemoveAllObjectsBlock;
  769. [self unlock];
  770. return block;
  771. }
  772. - (void)setDidRemoveAllObjectsBlock:(PINDiskCacheBlock)block
  773. {
  774. __weak PINDiskCache *weakSelf = self;
  775. dispatch_async(_asyncQueue, ^{
  776. PINDiskCache *strongSelf = weakSelf;
  777. if (!strongSelf)
  778. return;
  779. [strongSelf lock];
  780. strongSelf->_didRemoveAllObjectsBlock = [block copy];
  781. [strongSelf unlock];
  782. });
  783. }
  784. - (NSUInteger)byteLimit
  785. {
  786. NSUInteger byteLimit;
  787. [self lock];
  788. byteLimit = _byteLimit;
  789. [self unlock];
  790. return byteLimit;
  791. }
  792. - (void)setByteLimit:(NSUInteger)byteLimit
  793. {
  794. __weak PINDiskCache *weakSelf = self;
  795. dispatch_async(_asyncQueue, ^{
  796. PINDiskCache *strongSelf = weakSelf;
  797. if (!strongSelf)
  798. return;
  799. [strongSelf lock];
  800. strongSelf->_byteLimit = byteLimit;
  801. if (byteLimit > 0)
  802. [strongSelf trimDiskToSizeByDate:byteLimit];
  803. [strongSelf unlock];
  804. });
  805. }
  806. - (NSTimeInterval)ageLimit
  807. {
  808. NSTimeInterval ageLimit;
  809. [self lock];
  810. ageLimit = _ageLimit;
  811. [self unlock];
  812. return ageLimit;
  813. }
  814. - (void)setAgeLimit:(NSTimeInterval)ageLimit
  815. {
  816. __weak PINDiskCache *weakSelf = self;
  817. dispatch_async(_asyncQueue, ^{
  818. PINDiskCache *strongSelf = weakSelf;
  819. if (!strongSelf)
  820. return;
  821. [strongSelf lock];
  822. strongSelf->_ageLimit = ageLimit;
  823. [strongSelf unlock];
  824. [strongSelf trimToAgeLimitRecursively];
  825. });
  826. }
  827. - (void)lock
  828. {
  829. dispatch_semaphore_wait(_lockSemaphore, DISPATCH_TIME_FOREVER);
  830. }
  831. - (void)unlock
  832. {
  833. dispatch_semaphore_signal(_lockSemaphore);
  834. }
  835. @end
  836. @implementation PINBackgroundTask
  837. - (instancetype)init
  838. {
  839. if (self = [super init]) {
  840. #if !defined(PIN_APP_EXTENSIONS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0
  841. _taskID = UIBackgroundTaskInvalid;
  842. #endif
  843. }
  844. return self;
  845. }
  846. + (instancetype)start
  847. {
  848. PINBackgroundTask *task = [[self alloc] init];
  849. #if !defined(PIN_APP_EXTENSIONS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0
  850. task.taskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
  851. UIBackgroundTaskIdentifier taskID = task.taskID;
  852. task.taskID = UIBackgroundTaskInvalid;
  853. [[UIApplication sharedApplication] endBackgroundTask:taskID];
  854. }];
  855. #endif
  856. return task;
  857. }
  858. - (void)end
  859. {
  860. #if !defined(PIN_APP_EXTENSIONS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0
  861. UIBackgroundTaskIdentifier taskID = self.taskID;
  862. self.taskID = UIBackgroundTaskInvalid;
  863. [[UIApplication sharedApplication] endBackgroundTask:taskID];
  864. #endif
  865. }
  866. @end