KHolder.m 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. //
  2. // KHolder.m
  3. // KacheDemo
  4. //
  5. // Created by jiajun on 7/25/12.
  6. // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
  7. //
  8. #define Kache_Objects_Disk_Path @"Caches/Kache_objects"
  9. #import "KConfig.h"
  10. #import "KHolder.h"
  11. #import "KObject.h"
  12. #import "KPool.h"
  13. #import "KQueue.h"
  14. #import "KUtil.h"
  15. @interface KHolder ()
  16. // 正在进行归档的状态位
  17. @property (assign, atomic) BOOL archiving;
  18. @property (assign, atomic) BOOL cleaning;
  19. @property (strong, nonatomic) NSFileManager *fileManager;
  20. @property (strong, atomic) NSMutableArray *keys;
  21. @property (assign, nonatomic) NSUInteger size;
  22. @property (strong, nonatomic) NSMutableDictionary *objects;
  23. @property (strong, nonatomic) NSString *path;
  24. // 把数据写到磁盘
  25. - (void)archiveData;
  26. - (void)cleanExpiredObjects;
  27. @end
  28. @implementation KHolder
  29. @synthesize archiving = _archiving;
  30. @synthesize cleaning = _cleaning;
  31. @synthesize fileManager = _fileManager;
  32. // 缓存Key列表
  33. @synthesize keys = _keys;
  34. // 缓存大小
  35. @synthesize size = _size;
  36. // 缓存内容
  37. @synthesize objects = _objects;
  38. @synthesize path = _path;
  39. #pragma mark - init
  40. - (id)init
  41. {
  42. self = [super init];
  43. if (self) {
  44. self.objects = [[NSMutableDictionary alloc] init];
  45. self.keys = [[NSMutableArray alloc] init];
  46. self.size = 0.0f;
  47. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
  48. NSString *libDirectory = [paths objectAtIndex:0];
  49. self.path = [libDirectory stringByAppendingPathComponent:Kache_Objects_Disk_Path];
  50. return self;
  51. }
  52. return nil;
  53. }
  54. #pragma mark - private
  55. - (NSFileManager *)fileManager
  56. {
  57. return [NSFileManager defaultManager];
  58. }
  59. - (void)archiveData
  60. {
  61. self.archiving = YES;
  62. BOOL isDirectory = NO;
  63. if (! [[NSFileManager defaultManager] fileExistsAtPath:self.path isDirectory:&isDirectory]) {
  64. [self.fileManager createDirectoryAtPath:self.self.path
  65. withIntermediateDirectories:YES
  66. attributes:nil
  67. error:nil];
  68. }
  69. NSMutableArray *copiedKeys = [self.keys mutableCopy];
  70. while (0 < [copiedKeys count]) {
  71. // 归档至阈值一半的数据
  72. if ((ARCHIVING_THRESHOLD / 2) > self.size) {
  73. break;
  74. }
  75. NSString *key = [copiedKeys lastObject];
  76. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  77. NSData *data = [self.objects objectForKey:key];
  78. [data writeToFile:filePath atomically:YES];
  79. self.size -= data.length;
  80. [copiedKeys removeLastObject];
  81. [self.objects removeObjectForKey:key];
  82. }
  83. copiedKeys = nil;
  84. self.archiving = NO;
  85. }
  86. - (void)cleanExpiredObjects
  87. {
  88. self.cleaning = YES;
  89. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  90. if (self.keys && 0 < [self.keys count]) {
  91. for (int i = 0; i < [self.keys count] - 1; i ++) {
  92. NSString *tmpKey = [self.keys objectAtIndex:i];
  93. KObject *leftObject = [self objectForKey:tmpKey];
  94. if ([leftObject expiredTimestamp] < [KUtil nowTimestamp]) {
  95. [self.keys removeObject:tmpKey];
  96. if ([[self.objects allKeys] containsObject:tmpKey]) {
  97. [self.objects removeObjectForKey:tmpKey];
  98. }
  99. else {
  100. NSString *filePath = [self.path stringByAppendingPathComponent:tmpKey];
  101. [self.fileManager removeItemAtPath:filePath error:nil];
  102. }
  103. }
  104. else {
  105. break;
  106. }
  107. }
  108. }
  109. self.cleaning = NO;
  110. });
  111. }
  112. #pragma mark - public
  113. - (void)removeObjectForKey:(NSString *)key {
  114. [self.keys removeObject:key];
  115. [self.objects removeObjectForKey:key];
  116. }
  117. - (void)setValue:(id)value forKey:(NSString *)key expiredAfter:(NSInteger)duration
  118. {
  119. KObject *object = [[KObject alloc] initWithData:value andLifeDuration:duration];
  120. if (YES || self.archiving) {
  121. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  122. [object.data writeToFile:filePath atomically:YES];
  123. }
  124. else {
  125. [self.objects setValue:object.data forKey:key];
  126. self.size += [object size];
  127. }
  128. KObject *suchObject = [self objectForKey:key];
  129. // TODO sort the key by expired time.
  130. [self.keys removeObject:key];
  131. if (! self.cleaning && (0 < [self.keys count])) {
  132. [self cleanExpiredObjects];
  133. for (int i = [self.keys count] - 1; i >= 0; i --) {
  134. NSString *tmpKey = [self.keys objectAtIndex:i];
  135. KObject *leftObject = [self objectForKey:tmpKey];
  136. // 过期时间越晚
  137. if ([leftObject expiredTimestamp] <= [suchObject expiredTimestamp]) {
  138. if (([self.keys count] - 1) == i) {
  139. [self.keys addObject:key];
  140. }
  141. else {
  142. [self.keys insertObject:key atIndex:i + 1];
  143. }
  144. break;
  145. }
  146. }
  147. }
  148. if (! [self.keys containsObject:key]) {
  149. [self.keys insertObject:key atIndex:0];
  150. }
  151. // 超过阈值,归档
  152. if ((! self.archiving)
  153. && 0 < ARCHIVING_THRESHOLD
  154. && ARCHIVING_THRESHOLD < self.size) {
  155. [self archiveData];
  156. }
  157. }
  158. - (id)valueForKey:(NSString *)key
  159. {
  160. KObject *object = [self objectForKey:key];
  161. if (object && ! [object expired]) {
  162. return [object value];
  163. }
  164. // No such object.
  165. return nil;
  166. }
  167. - (KObject *)objectForKey:(NSString *)key
  168. {
  169. if ([[self.objects allKeys] containsObject:key]) {
  170. return [[KObject alloc] initWithData:[self.objects objectForKey:key]];
  171. }
  172. else {
  173. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  174. if ([self.fileManager fileExistsAtPath:filePath isDirectory:NO]) {
  175. [self.objects setValue:[NSData dataWithContentsOfFile:filePath] forKey:key];
  176. [self.fileManager removeItemAtPath:filePath error:nil];
  177. return [[KObject alloc] initWithData:[self.objects objectForKey:key]];
  178. }
  179. }
  180. return nil;
  181. }
  182. // Convert object to NSDictionary.
  183. - (NSDictionary *)serialize
  184. {
  185. return [NSDictionary dictionaryWithObjectsAndKeys:
  186. self.objects, @"objects",
  187. self.keys, @"keys",
  188. [NSString stringWithFormat:@"%d", self.size], @"size",
  189. nil];
  190. }
  191. // Convert NSDictionary to object.
  192. - (void)unserializeFrom:(NSDictionary *)dict
  193. {
  194. if ([[dict allKeys] containsObject:@"objects"]
  195. && [[dict allKeys] containsObject:@"keys"]
  196. && [[dict allKeys] containsObject:@"meta"]) {
  197. self.objects = [dict objectForKey:@"objects"];
  198. self.keys = [dict objectForKey:@"keys"];
  199. self.size = [[dict objectForKey:@"size"] intValue];
  200. }
  201. }
  202. @end