KHolder.m 7.2 KB

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